为什么我不能从 const String& 方法返回 NULL?
Why can't I return NULL from a const String& method?
我有以下方法声明: 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
有人可以帮助我理解这一点吗?这里有没有一些我不完全理解的恒定正确性概念?
NULL
不是 const String
类型的对象,所以当需要引用 const String
时,当然不能返回它。事实上,引用的主要优点之一是它们不能(永远)NULL
。
重新定义函数以返回 const String *
,或返回空String
。
NULL 是一个指针(或者从技术上讲,整数值 0,可以转换为指针/从指针转换,nullptr
是值为零的指针)。
std::string&
不是指针(或整数),因此不能对它使用NULL
。您可以返回""
或"Unknown"
或类似的东西。
相关文章:
- 从父类方法返回子类对象
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 让bool方法返回其他整数
- 不能将方法返回的值用于另一个方法
- 从私有成员变量的成员方法返回unique_ptr
- 我的模板类方法返回错误类型?
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 我无法使用C++指针指向类方法返回的 std::vector
- 对象引用中的字段以不同的方法返回不同的值
- 类方法返回指向具有模板的类成员的指针
- 如何将字符串从 C++/CLI 方法返回到调用它的非托管C++
- 从工厂方法返回的ComPtr的引用计数增加两次
- 如何使用 SFINAE 从 end() 方法返回 (const_) 迭代器
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- 从类方法返回 "const char*" 作为 std::string&
- 如何使用 "get" 方法返回类的私有 std::unique_ptr 成员
- 可能从单个方法返回不同类型的对象
- qml 未知方法返回类型:ArchiveFile*,即使调用了 qmlRegisterUncreatableType
- 如何从方法返回静态常量 int std::array?
- 当从其他方法返回 vector 时,C++无法访问矢量元素