I have the following method declaration: 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
.
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?
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. In fact, one of the major advantages of references is that they can't (ever) be NULL
.
Re-define the function to return const String *
, or return an empty 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).
A std::string&
is not a pointer (or an integer), so you can't use NULL
for it. You could return ""
or "Unknown"
or something like that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.