Rol*_*and 3 c++ overriding const reference
给出以下代码:
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 gets called
const int& get() const;
Run Code Online (Sandbox Code Playgroud)虽然与
int* get();
const int& get() const;
Run Code Online (Sandbox Code Playgroud)
我们有一个编译器错误。
让我感到困惑的是所有这些行为背后的原因。
当你同时拥有const和不const具有相同的参数相同的功能,其中一个被调用的超载取决于只在const其上你调用该函数的对象的湖。因此,调用非常量a 必须调用非const重载。
这是完全相同的情况:
void foo(int *p);
void foo(const int *p);
int main()
{
int i;
const int ci;
foo(&i); // Calls the first overload
foo(&ci); // Calls the second overload
}
Run Code Online (Sandbox Code Playgroud)
甲const-qualified函数可以被称为非对const-qualified对象,但是这需要一个“非const为const”的转换。如果存在不需要这种转换的重载(更好的匹配),则将是首选。
| 归档时间: |
|
| 查看次数: |
913 次 |
| 最近记录: |