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

Why can't I return NULL from a const String& method?

本文关键字:方法 返回 NULL String 不能 const 为什么      更新时间:2023-10-16

我有以下方法声明: 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"或类似的东西。