const类型对象只能调用const类型函数

来源:互联网 发布:皇太子的王子网络剧01 编辑:程序博客网 时间:2024/05/21 07:46

例子: 

 class A { 

 public: 

 A():num(2) { } 

 ~A() { } 

 void setnum() const { num = 10; } 

 void getnum() const{ printf("%d\\n",num); } 

 private: 

 int num; 

}; 

int main() 

{ A b; 

 b.setnum(); 

 return 0; } 

可以注意到,编译以上这段代码会出现编译错误(l-value specifies const object)!,避免错误的方式为:

方法1.重新定义变量num为:mutable int num;(在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中。)

方法2.修改setnum函数为void setnum() const {   } 

因为setnum函数被声明为const了,这样一来,在编译器的编译过程中,就将这个类方法中的影藏参数this转换成了const this,这样一来,自然就不能对类成员进行修改了。 现在在来看下返回值为const的函数有什么作用: 

class A
{
    public:
        A():num(2)
        {
 
        }
        ~A()
        {
 
        }
        void setnum()
        {
            num = 10;
        }
        void getnum() const{
            printf("%d\\n",num);
        }
    private:
        int num;
};
 
class B
{
    public:
        B()
        {
 
        }
        ~B()
        {
 
        }
        const A* get()
        {
            A *p = new A();
            return p;
        }
         
};
 
int main()
{
    B b;
    b.get()->getnum();
    b.get()->setnum();
    return 0;
}
现在我们通过类B的方法get()来获得一个类A的实体const对象 ,你会发现程序也编不过,
原因其实类似,const类型的对象,不能调用自身的非const成员函数,但是可以调用自己的const成员函数。

0 0
原创粉丝点击