【发布时间】:2011-02-11 18:10:31
【问题描述】:
以下代码无法编译:
#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;
}
我收到以下错误:
const1.cc:11: error:
invalid initialization of reference of type 'const std::string&'
from expression of type 'std::string*
这确实有些道理,因为foo 不是const Foo 类型,而只是Foo,所以编译器想要使用非常量函数。但是,为什么它不能通过查看我分配给它的(类型)变量来识别我想调用 const GetString 函数?我发现这种情况令人惊讶。
【问题讨论】:
-
如果您要抛出 insults,请准备好让编译器询问您为什么不够聪明,无法为您的 const 重载成员定义兼容的返回类型函数 ;-) 如果你想在非常量对象上调用函数的 const 版本,你 static_cast:
const std::string &s = static_cast<const Foo&>(foo).GetString(); -
实际上,现在我对编译器提出的一系列恶搞 StackOverflow 问题有了一个想法:“为什么我的程序员总是忘记将基类析构函数设为虚拟?”、“指针:为什么不能人类要么弄清楚它们,要么干脆停止使用它们?”,“我人类的代码总是无法编译,无论他尝试什么。我有错误吗?”等等。可能永远不会有任何意义。
-
@Steve:好主意。随意借用/修改/扩展我的答案中的代码 sn-p。
标签: c++ function constants overloading