aaj*_*tak 13 c++ struct reference
struct Div
{
int i;
int j;
};
class A
{
public:
A();
Div& divs;
};
Run Code Online (Sandbox Code Playgroud)
在我的构造函数定义中,我有以下内容
A::A() : divs(NULL)
{}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Error72 error C2354:
'A::divs' : initialization of reference member requires a temporary variable
Run Code Online (Sandbox Code Playgroud)
Mik*_*our 33
必须初始化引用以引用某些内容; 它不能引用任何内容,因此你不能默认构造一个包含一个的类(除非像其他人建议的那样,你定义一个全局的"null"值).您将需要一个给出的构造函数Div来引用:
explicit A(Div &d) : divs(d) {}
Run Code Online (Sandbox Code Playgroud)
如果您希望它能够为"null",那么您需要一个指针,而不是一个引用.
Rus*_*ist 12
div是引用,而不是指针.您不能将其设置为NULL,它必须指向某种实际对象.在这里做的最好的事情可能是定义一个Div的静态/全局实例,你可以任意定义为"Null Div"(将其值设置为你不太可能使用的东西)并将div初始化为该值.像这样的东西:
struct Div
{
int i;
int j;
};
Div NULL_DIV = { INT_MAX, INT_MAX };
class A
{
public:
A();
Div& divs;
};
A::A() : divs(NULL_DIVS)
{
}
Run Code Online (Sandbox Code Playgroud)
或者,或者,只是使div成为指针而不是引用.
*请注意,除非丢弃const,否则不能使用const引用,因为默认情况下编译器不允许您将cosnt引用赋给非const引用.
在"英语"中:引用指的是某种东西.它不能引用任何内容(null).这就是为什么引用使用指针更安全的原因.