c++ - 为什么我不能从 const String& 方法返回 NULL?

标签 c++ constants

我有以下方法声明: 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/

相关文章:

c++ - 在 Windows 10 上显示触摸友好菜单

C++ const 难题

c++ - 为什么对指针参数包进行 const 限定是错误的?

c++ - const、指针、typedef 和星号

php - 尝试在php类中给常量赋值会导致意外的T_variable

C++ 对非 Const 对象的 Const 引用与对非 Const 对象的非 Const 引用之间的区别

c++ - C++中char[]的子串

c++ - 将 volatile 数据与未为 volatile 数据重载的方法一起使用

c++ - 在 C++ 中使用 scanLine() 方法存储所有 QImage 的像素

c++ - BST 中大于给定 KEY 的节点数