C++常成员函数 - const 关键字

转自http://www.cnblogs.com/this-543273659/archive/2011/07/18/2109922.html


C++常成员函数- const 关键字

一、常成员函数详解

声明:<类型标志符>函数名(参数表)const

说明:

(1)const是函数类型的一部分,在实现部分也要带该关键字。

(2)const关键字可以用于对重载函数的区分。

3常成员函数不能更新类的成员变量,也不能调用该类中没有用const修饰的成员函数,只能常成员函数

A、通过例子来理解const是函数类型的一部分,在实现部分也要带该关键字。

classA{

private:

     int w,h;

public:

     int getValue() const;

     int getValue();

     A(int x,int y)

     {

         w=x,h=y;

     }

     A(){}

};

intA::getValue() const     //实现部分也带该关键字

{

     returnw*h; //????

}

voidmain()

{

     Aconst a(3,4);

     A c(2,6);

cout<<a.getValue()<<c.getValue()<<"cctwlTest";

system("pause");

}

B、通过例子来理解const关键字的重载

classA{

private:

     int w,h;

public:

int getValue() const

{

         return w*h;

     }

     int getValue(){

         return w+h;

     }

     A(int x,int y)

     {

         w=x,h=y;

     }

     A(){}

};

voidmain()

{   

     A const a(3,4);

     Ac(2,6);

     cout<<a.getValue()<<c.getValue()<<"cctwlTest"; //输出128

     system("pause");

}

C、通过例子来理解常成员函数不能更新任何数据成员

classA{

private:

     int w,h;

public:

     int getValue() const;

     int getValue();

     A(int x,int y)

     {

         w=x,h=y;

     }

     A(){}

};

intA::getValue() const

{

    w=10,h=10;//错误,因为常成员函数不能更新任何数据成员

     return w*h;

}

intA::getValue()

{

     w=10,h=10;//可以更新数据成员

     return w+h;

}

voidmain()

{

      A const a(3,4);

     Ac(2,6);

     cout<<a.getValue()<<endl<<c.getValue()<<"cctwlTest";        

 system("pause");

}

D、通过例子来理解

1、常成员函数可以被其他成员函数调用。

2、但是不能调用其他非常成员函数。

3、可以调用其他常成员函数。

classA{

private:

     int w,h;

public:

     int getValue() const

{

   return w*h + getValue2();//错误的不能调用其他非常成员函数。

}

   int getValue2()

     {

        

         return w+h+getValue();//正确可以调用常成员函数

     }

    

     A(int x,int y)

     {

         w=x,h=y;

     }

     A(){}

};

voidmain()

{

     A const a(3,4);

     A        c(2,6);

cout<<a.getValue()<<endl<<c.getValue2()<<"cctwlTest";        

system("pause");

}


------------------------------------------------------------------------------------------------------------

在const成员函数内,成员变量的修改是不允许的。但是如果我们的需求一定要改变成员变量时,可以用mutable(可变的)关键字来实现。mutable释放掉了成员变量的constness约束。下面看个例子

class CTextBlock{
    public:
    ...
   std::size_t length() const;
   private:
   char* pText;
   mutable std::size_t textLength;
   mutable bool lengthIsValid;
};
std::size_t CTextBlock::length() const
{
    if(!lengthIsValid)
    {
        textLength = std::strlen(pText);
        lengthIsValid  = true;
    }
    return textLength;

}

现在就可以改变textLength 和lengthIsValid的值了


参考: 《effective c++》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值