在 C++ 中将对成员的引用初始化为 NULL
是否可以在 C++ 中将引用成员初始化为 NULL?
我正在尝试这样的事情:
class BigClass
{
private:
Object m_inner;
public:
const Object& ReadOnly;
BigClass() : ReadOnly(NULL)
{
Do stuff.
}
};
我知道如果我将“ReadOnly”初始化为对象的真实引用,我可以做到这一点,但是当我想在那里放入“NULL”时,我收到错误:
“无法从 'int' 转换为 'const Object &'
我该如何解决这个问题?
Is it possible to initialize a reference member to NULL in c++?
I'm trying to something like this:
class BigClass
{
private:
Object m_inner;
public:
const Object& ReadOnly;
BigClass() : ReadOnly(NULL)
{
Do stuff.
}
};
I know I can do this if I initialize "ReadOnly" to a real reference of an object, but when I want to put in there "NULL", i get the error:
"cannot convert from 'int' to 'const Object &'
How can I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不可以,在 C++ 中引用不能为
NULL
。1可能的解决方案包括:
Object
实例,可用于指示“无对象”。[1] 来自 C++ 11 标准:
No, references cannot be
NULL
in C++.1Possible solutions include:
Object
instance that can be used to indicate "no object".[1] From the C++11 standard:
你无法“解决”这个问题。如果您希望该成员不指向任何内容,请使用指针。
引用必须初始化为真实对象,它们不能“指向任何地方”。
You cannot "solve" this. Use a pointer if you want to be able to have that member not point to anything.
References must be initialized to a real object, they cannot "point nowhere".
这是可以做到的,但几乎可以肯定这是一个非常糟糕的主意。做到这一点的方法是取消引用一个适当类型的 NULL 指针,这已经表明这是一个坏主意:此时您会遇到未定义的行为,但是,通常倾向于“工作”。
在 C++ 中,引用意味着始终引用实际对象。这与其他编程语言不同,在其他编程语言中,“引用”实际上相当于 C++ 中的指针(通常没有指针算术之类的东西)。您可能真正想要的(不幸的是,您没有说出您试图实现的目标,而是询问了问题的解决方案,这可能是误导方法的一部分)是使用指针:
It can be done but it is almost certainly an extremely bad idea. The way to do it is to dereference a suitably typed
NULL
pointer which already shows that it is a bad idea: you arrive at undefined behavior at this point which, however, typically tends to "work".In C++ references are meant to always refer to an actual object. This is different to other programming languages where "references" are actually the equivalent of pointers in C++ (typically without things like pointer arithmetic). What you probably actually want (you unfortunately didn't say what you try to achieve it but asked about a solution to a problem which is probably part of a misguided approach) is to use a pointer instead:
它在编写单元测试时很有用。这是唯一应该做的地方,但在那里,它非常有帮助。
在这里,我正在测试使用
MockClass
的代码,而不是MockClass
本身。它不是万能药,但可以提供帮助。另外,GoogleMock 可能是您的朋友。
It's useful in writing unit-tests. That is the only place it should be done, but there, it's quite helpful.
Here, I am testing code which uses
MockClass
, notMockClass
itself.It's not a panacea, but it can help. Also, GoogleMock might be your friend if you are mocking "concrete" classes.
使用指针:-
const 对象* pReadOnly;
Use a pointer:-
const Object* pReadOnly;