在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++?

本文关键字:const 记为 方法 另一个 调用 何解析 一个 如果 c++ 两个      更新时间:2023-10-16
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)上调用,如果对象表达式是