📜  是否可以在不使用声明进行初始化的情况下声明C++参考成员?

📅  最后修改于: 2021-05-30 03:03:25             🧑  作者: Mango

对于许多读者来说,这听起来可能是一样的,即

class_type *var = NULL;
*var = &some_work;

is same as

class_type *var = &some_work;

但实际上并非如此。当声明和初始化在同一步骤中完成时,编译器将调用复制构造函数,而在另一步骤中,编译器将调用默认构造函数。
为了理解这一点,让我们考虑一个示例:
示例1:在声明的同一步骤中未完成初始化的情况

CPP
#include 
using namespace std;
 
class A {
    int& p;
 
    // Note:basically it is
    // supposed to be an error
    // because this reference
    // member p is not initialized
    // with some variable at the same
    // step of its declaration. But it
    // will run in this case. For us,
    // this is the declaration but
    // not for compiler
 
public:
 
    // this line
    // means int &p=w, so p and w
    // both are same. Compiler considers
    // this step as declaration and
    // initialization is done at
    // same step.
    A(int w): p(w)
    {
        cout << p;
    }
};
int main()
{
    A obj(10);
    return 0;
}


CPP
#include 
using namespace std;
 
class A {
    int& p;
 
public:
 
    // In this step,
    // compiler will see only
    // declaration not initialization.
    // Therefore this code will
    // give an error.
    A(int w)
    {
        p = w;
        cout << p;
    }
};
int main()
{
    A obj(10);
    return 0;
}


输出:

10

示例2:使用声明完成初始化时

CPP

#include 
using namespace std;
 
class A {
    int& p;
 
public:
 
    // In this step,
    // compiler will see only
    // declaration not initialization.
    // Therefore this code will
    // give an error.
    A(int w)
    {
        p = w;
        cout << p;
    }
};
int main()
{
    A obj(10);
    return 0;
}

编译错误:

prog.cpp: In constructor 'A::A(int)':
prog.cpp:8:5: error: uninitialized reference member in 'int&' [-fpermissive]
     A(int w)
     ^
prog.cpp:5:10: note: 'int& A::p' should be initialized
     int& p;
          ^

注意:在此代码中,一旦创建对象,编译器便会通过运行类A的构造函数将内存分配给p。现在我们知道,引用变量需要在同一步骤中初始化,因此它将弹出一条错误消息,称为“引用成员未初始化”。
正如我们在代码1中所看到的,初始化不是在声明的同一步骤完成的,但是我们的代码仍在运行。但一般来说,“引用成员应在同一步骤中初始化和声明”是一条规则。
因此,上述问题的答案是肯定和否定。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”