是否可以在c++中将引用成员初始化为NULL?
我正在尝试这样的事情:
class BigClass
{
private:
Object m_inner;
public:
const Object& ReadOnly;
BigClass() : ReadOnly(NULL)
{
Do stuff.
}
};
我知道如果我将“ReadOnly”初始化为一个对象的真实引用,我可以做到这一点,但是当我想在那里输入“NULL”时,我得到了错误:
"cannot convert from 'int' to 'const Object &'
我该如何解决这个问题?
最佳答案
不,C++ 中的引用不能为 NULL
。1
可能的解决方案包括:
- 使用指针而不是引用。
- 有一个虚拟的
Object
实例,可以用来表示“没有对象”。
[1] 来自 C++11 standard :
[dcl.ref] [...] a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.
关于c++ - 在 C++ 中初始化对成员的引用为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9055778/