Fra*_*ank 4 c++ overloading const function
以下代码无法编译:
#include <iostream>
class Foo {
std::string s;
public:
const std::string& GetString() const { return s; }
std::string* GetString() { return &s; }
};
int main(int argc, char** argv){
Foo foo;
const std::string& s = foo.GetString(); // error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
const1.cc:11: error:
invalid initialization of reference of type 'const std::string&'
from expression of type 'std::string*
Run Code Online (Sandbox Code Playgroud)
它确实有一定意义,因为foo它不是类型const Foo,只是Foo,因此编译器想要使用非const函数.但是,为什么不能通过GetString查看我赋给它的(类型)变量来识别我想调用const 函数?我发现这种情况令人惊讶.
CB *_*ley 10
返回类型是由实际调用的重载函数确定的,它从不构成重载决策本身的一部分.(如果没有使用返回类型怎么办?)
const不是返回值的问题,因为您可以将非const对象绑定到const引用,事实上您的函数返回一个您不解引用的指针.
至于foo是不是const,非const GetString()叫-它是一个非更好的匹配const对象.你需要:
const std::string& s = *foo.GetString();
Run Code Online (Sandbox Code Playgroud)