C++中,const对象只能调用const成员函数,原因是什么呢?下面我们针对如下例子并对其进行分析进而理解其中缘由:
#include <iostream> #include <string> using namespace std; class MyInt{ private: int i; public: MyInt(){ } MyInt(int i) :i(i){ } MyInt& operator++(){ this->i += 1; return *this; } const MyInt operator++(int){ MyInt oldInt = MyInt(*this); this->i += 1; return oldInt; } void show(){ cout << i << endl; } }; int main(){ MyInt mi(10), mi2(100); mi2++.show(); return 0; }编译报错: 我们可以看到,编译器报错为无法将const MyInt转换为MyInt&,说明const对象调用非const成员函数的时候出现了一些转换问题,下面我们就来进行一下分析:
const对象无法调用非const成员函数: void show()等价于void show(MyInt* this),非const对象那个mi2调用时即mi2.show(),即传递了一个非const对象那个指针即MyInt* this进入,因此show函数执行成功! const对象呢?const MyInt mi3(10),现在等价于当前传递进去的参数类型是const MyInt*,此时将该指针传递给MyInt*存在一个转化失败问题,所以const成员对象不能调用非const成员对象。const对象可以调用const成员函数: const对象可以调用const成员函数,因为const成员函数默认参数为const MyInt* this,我们创建const对象,即传递进去的指针仍旧为const MyInt*,所以调用成功。