2
void testMethod(){
  cout<<"Normal Method";
}

void testMethod() const{
     cout<<"Const Method";
}

which of these will be called by call to testMethod()? When I tried the first was called. But how is this decided and it can't always be the first, otherwise there is no point in treating these two as different functions.

4

1 回答 1

3

If the member function is called through a reference to const or a pointer to const, or if it is called directly on an object whose type is const-qualified, the overload qualified as const will be picked. Otherwise, the overload not qualified as const will be picked.

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

In more formal terms, paragraph 9.3.2/3 of the C++11 Standard specifies (in the quote, cv stands for const-or-volatile, and you can ignore the volatile part for the purposes of your question):

A cv-qualified member function can be called on an object-expression (5.2.5) only if the object-expression is as cv-qualified or less-cv-qualified than the member function [...]

于 2013-05-27T14:58:53.030 回答