Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’

[c-sharp]  view plain copy
  1. class Point3d  
  2. {  
  3. public:  
  4.     Point3d(float x=0.0,float y=0.0,float z=0.0)  
  5.         :_x(x),_y(y),_z(z)  
  6.     {  
  7.     }  
  8.   
  9.     float GetX() {return _x;}  
  10.     float GetY() {return _y;}  
  11.     float GetZ() {return _z;}  
  12.   
  13. private:  
  14.     float _x,_y,_z;  
  15. };  
  16.   
  17. inline ostream& operator<<(ostream&out,const Point3d& pd)  
  18. {  
  19.     out<<pd.GetX()<<" "<<pd.GetY()<<" "<<pd.GetZ()<<endl;  
  20.   
  21.     return out;  
  22. }  

上述的代码是导致错误的例子。错误主要的原因是const类型的对调用非const类型的方法导致的。

由于const对象在调用成员函数时,会将this指针强制转换成const this指针,它调用成员函数时会去找对应的const Get*函数,而编译器无法将非const类型的Get*函数转换成const类型的Get*函数,因此出现编译错误。

解决方法就是将Get*函数转化为const类型的函数

在对应函数后面加上const关键字

[c-sharp]  view plain copy
  1. class Point3d  
  2. {  
  3. public:  
  4.     Point3d(float x=0.0,float y=0.0,float z=0.0)  
  5.         :_x(x),_y(y),_z(z)  
  6.     {  
  7.     }  
  8.   
  9.     float GetX() const{return _x;}  
  10.     float GetY() const{return _y;}  
  11.     float GetZ() const{return _z;}  
  12.   
  13. private:  
  14.     float _x,_y,_z;  
  15. };  
  16.   
  17. inline ostream& operator<<(ostream&out,const Point3d& pd)  
  18. {  
  19.     out<<pd.GetX()<<" "<<pd.GetY()<<" "<<pd.GetZ()<<endl;  
  20.   
  21.     return out;  
  22. }  

因此书《深度探索C++对象模型》第一章关于对象模型 P2页举得例子有问题的。它的代码是上面出错的代码。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值