很多书上说可以把函数" void getI( ) const "看作是函数 " void getI( ) "的一个重载。
以下实验表明,对象a会调用普通成员函数" void getI( ) ",请问这是为什么?C++为什么会如此设计?如何让对象a( )(普通对象,非常对象)调用" void getI( ) const " ?
#include <iostream>
#include <string>
using namespace std;
class A {
const int i;
int j;
public:
A():i(1), j(2) { }
void getI() const { cout << j; }
void getI() { cout << j + 1; }
};
int main() {
A a;
a.getI();
}
谢谢!
没什么特别好的方法,你可以通过一个临时的const引用来调用到带有const的成员函数。