给出以下代码:
class A
{
public:
A(): value( 0 ) {}
int* get()
{
return &value;
}
const int& get() const
{
return value;
}
private:
int value;
};
int main()
{
A a;
const int& ref_value = a.get();
}
Run Code Online (Sandbox Code Playgroud)
导致以下编译错误:
prog.cpp: In function 'int main()':
prog.cpp:23:35: error: invalid conversion from 'int*' to 'int'
const int& ref_value = a.get();
^
Run Code Online (Sandbox Code Playgroud)
似乎带有const修饰符的重载get()方法确实会被完全忽略,并且编译器仅看到它的非const定义。这是可以理解的,因为对象不是常数。一个解决办法是让一个对象不变。尽管还有其他两种解决方案可以使代码可编译:
通过使用其他名称或添加的其他参数来更改const get()方法的签名。
int* get();
const int& get_changed() const; <-- this gets called
Run Code Online (Sandbox Code Playgroud)更改非const get()方法以返回引用而不是指针。
int& get(); <-- this …Run Code Online (Sandbox Code Playgroud)