简体   繁体   English

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

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

I have the following method declaration: const String& MyClass::GetAspect(const String& strKey) const 我有以下方法声明: const String& MyClass::GetAspect(const String& strKey) const

In this method, we've decided to do a null-pointer check before doing some stuff; 在这种方法中,我们决定在做一些事情之前先做一个空指针检查。 if the pointer inside this method is null , we want to just return null . 如果此方法内的指针为null ,则只想返回null

However, I get the following error: 但是,出现以下错误:

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

Could someone help me understand this? 有人可以帮我理解吗? Is there some const-correctness concept I don't fully understand here? 这里有一些我不完全理解的const正确性概念吗?

NULL is not an object of type const String , so of course you can't return it when a reference to const String is expected. NULL不是const String类型的对象,因此,当需要引用const String时,当然不能将其返回。 In fact, one of the major advantages of references is that they can't (ever) be NULL . 实际上,引用的主要优点之一是它们不能(永远)为NULL

Re-define the function to return const String * , or return an empty String . 重新定义该函数以返回const String *或返回一个空String

NULL is a pointer (or technically, the integer value zero, which can be converted to/from a pointer, nullptr is a pointer with the value zero). NULL是一个指针(或者从技术上讲,它是可以从指针转换为整数的零值, nullptr是值为零的指针)。

A std::string& is not a pointer (or an integer), so you can't use NULL for it. std::string&不是指针(或整数),因此不能使用NULL You could return "" or "Unknown" or something like that. 您可以返回"""Unknown"或类似的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM