我有以下方法声明:
const String& MyClass::GetAspect(const String& strKey) const
在这个方法中,我们决定在做一些事情之前做一个空指针检查;如果此方法中的指针为 null
,我们只想返回 null
。
但是,我收到以下错误:
myclass.cpp(222) : error C2440: 'return' : cannot convert from 'int' to 'const String &'
Reason: cannot convert from 'int' to 'const String'
No constructor could take the source type, or constructor overload resolution was ambiguous
有人能帮我理解一下吗?是否有一些我在这里不完全理解的 const-correctness 概念?
最佳答案
NULL
不是 const String
类型的对象,所以当对 const String
的引用是预期的。事实上,引用的主要优点之一是它们不能(永远)为 NULL
。
重新定义返回const String *
的函数,或者返回一个空的String
。
关于c++ - 为什么我不能从 const String& 方法返回 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700041/