const函数

第一种情况:const对象调用非const成员函数

view plaincopy to clipboardprint?
class A 

public: 
A(int N = 0); 
void Fun(); 
private: 
int n; 
}; 
A::A(int N):n(N) 


void A::Fun() 

cout << n << endl; 

int  _tmain (int argc, _TCHAR* argv[]) 

A a; 
a.Fun(); 

const A &b = a; 
b.Fun();//const引用的对象调用非const成员函数 

//const A a; 
//a.Fun();//const对象调用非const成员函数 

cin.get(); 
return 0; 


当使用const对象调用非const成员函数时编译会报错:error C2662: 'A::Fun' : cannot convert 'this' pointer from 'const A' to 'A &'

报错原因:因为const对象在调用成员函数 时会隐含的把实参把中*this修改成const class * const this,以导致非const成员函数在接收时还是使用了class *const this接收,结果就是把const的指针赋给非const的指针

修正方法:以前错误只需在对象的成员函数后面加上const即可

view plaincopy to clipboardprint?
class A 

public: 
A(int N = 0); 
void Fun() const; 
private: 
int n; 
}; 
A::A(int N):n(N) 


void A::Fun() const 

cout << n << endl; 


第二种情况:在const成员函数中修改非const成员

view plaincopy to clipboardprint?
class A 

public: 
A(int N = 0); 
void Fun() const; 
protected: 
private: 
int n; 
}; 
A::A(int N):n(N) 


void A::Fun() const 

n = 100;//在const成员函数中修改了成员变量n的值 
cout << n << endl; 

同样,在编译此类时会报错:error C2166: l-value specifies const object

原因:在const的成员函数中修改了成员变量的值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值