c++常量成员函数详解

来源:互联网 发布:php导入excel带进度条 编辑:程序博客网 时间:2024/04/28 06:04
/*************************************************
 *    常量成员函数的含义(成员函数 + const)
 *                
 *          在类的 非 常量成员函数中,this指针类型是 X *const(
 *    针常量),而在 常量成员函数中,this指针类型是const X *const
 *    不能被修改,这就是常量成员函数和非常量成员函数的区别.
************************************************
*/

//例1
class 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,这将允许
 *    它们的值可以被常量成员函数(当然也包括成员函数)所修改.
************************************************
*/

//例2
class X
{
private:
    
static int expensiveOperation();
    
int *buffer_;
    mutable 
bool isComputed_; //注意 mutable
    mutable int computedValue_; //注意 mutable
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_;
}
;

/*************************************************
 *    下面通过操作符的重载来深刻理解常量成员函数
************************************************
*/

//例3
class 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//左边的参数是常量
}
;
原创粉丝点击