c++常量成员函数详解时间:2022-10-29 13:15:21/************************************************* * 常量成员函数的含义(成员函数 + const) * * 在类的 非 常量成员函数中,this指针类型是 X *const(指 * 针常量),而在 常量成员函数中,this指针类型是const X *const * 不能被修改,这就是常量成员函数和非常量成员函数的区别.*************************************************///例1class X{private: static int expensiveOperation(); int *buffer_; bool isComputed_; int computedValue_;public: X():buffer_(0),isComputed_(false) {} //... void setBuffer() { int *tmp = new int[MAX]; delete[] buffer_; buffer_ = tmp; } void modifyBuffer(int index,int value) const //相当不道德 -_-! { buffer_[index] = value; } int getValue() const { if(!isComputed) computedValue_ = expensiveOperation(); //错误 isComputed_ = true; //错误 } return computedValue_;};/************************************************* * 如果我们需要在常量函数中修改类成员怎么办? * 类的非静态变量数据成员可以声明为mutable,这将允许 * 它们的值可以被常量成员函数(当然也包括成员函数)所修改.*************************************************///例2class X{private: static int expensiveOperation(); int *buffer_; mutable bool isComputed_; //注意 mutable mutable int computedValue_; //注意 mutablepublic: X():buffer_(0),isComputed_(false) {} //... void setBuffer() { int *tmp = new int[MAX]; delete[] buffer_; buffer_ = tmp; } void modifyBuffer(int index,int value) const //相当不道德 -_-! { buffer_[index] = value; } int getValue() const { if(!isComputed) computedValue_ = expensiveOperation(); //正确 isComputed_ = true; //正确 } return computedValue_;};/************************************************* * 下面通过操作符的重载来深刻理解常量成员函数*************************************************///例3class X{public: //... int &operator [](int index); // ① const int &operator [](int index) const; //② //...};void main(){ int i = 10; X a; a[5] = i; //重载 ① const X b; i = b[5]; //重载 ②}class X{public: X operator + (const X &rightArg); //左边的参数是非常量 X operator + (const X &rightArg) const; //左边的参数是常量};