在c++中,如果有两个同名的方法,一个标记为const,另一个标记为非const,则如何解析方法调用
How is a method call resolved if the there are two methods with same name, one marked const and the other not, in C++?
void testMethod(){
cout<<"Normal Method";
}
void testMethod() const{
cout<<"Const Method";
}
对testMethod()
的调用将调用哪些?当我打第一个电话的时候。但是这是如何决定的,它不能总是第一个,否则把这两个当作不同的函数就没有意义了。
如果通过对const
的引用或指向const
的指针调用成员函数,或者直接在类型为const
限定的对象上调用成员函数,则选择限定为const
的重载。否则,将选择不符合const
的过载。
X x;
x.testMethod(); // Calls the non-const version
X const& y = x;
y.testMethod(); // Calls the const version
X* z = &x;
z->testMethod(); // Calls the non-const version
X const w;
w.textMethod(); // Calls the const version
在更正式的术语中,c++ 11标准的第9.3.2/3段规定(在引号中,cv
代表const
-或- volatile
,为了您的问题,您可以忽略volatile
部分):
cv限定的成员函数只能在对象表达式(5.2.5)上调用,如果对象表达式是
相关文章:
- 将 const 转换为 const char* 无效,我该如何解决?使用 gcc7 时失败
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 编译器可以静默地从 const 转换为 const 和,反之亦然吗?
- 从 Object<const T> 转换为 Object<t>
- 错误:无法将const字符串转换为参数1的const char*为size_t strlen(const char*)
- 将 const 传递为这样时出错
- 为什么在设置类成员时会自动从 const 转换为 non-const 并发生?
- 同时向下投递并从 const 转换为非 const
- 没有匹配的操作数[template]/无法从Type const*转换为Type
- static const转换为c++共享库中的对象.是进程间共享的吗?
- 无法从 *const 转换为 &in += 运算符
- C2664 无法在 Qt C++ 中将参数 1 从用户 *const 转换为用户
- C++:以"const pointer"为成员的列表与以"pointer to const"为成员的列表
- 将const复制为char*
- 错误:将(const A)传递为(this)
- const转换为非const或非const转换为const
- C++11:无法将参数从'T *const'转换为'T *&&'
- 复制构造函数将const转换为非const
- c++将非const引用为temporary:是否合法?
- 对于obj(obj*const a=obj const*b),int*const a=int const*b是否为tru