Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
2010-04-20 09:58
483 查看
class Point3d { public: Point3d(float x=0.0,float y=0.0,float z=0.0) :_x(x),_y(y),_z(z) { } float GetX() {return _x;} float GetY() {return _y;} float GetZ() {return _z;} private: float _x,_y,_z; }; inline ostream& operator<<(ostream&out,const Point3d& pd) { out<<pd.GetX()<<" "<<pd.GetY()<<" "<<pd.GetZ()<<endl; return out; }
上述的代码是导致错误的例子。错误主要的原因是const类型的对调用非const类型的方法导致的。
由于const对象在调用成员函数时,会将this指针强制转换成const this指针,它调用成员函数时会去找对应的const Get*函数,而编译器无法将非const类型的Get*函数转换成const类型的Get*函数,因此出现编译错误。
解决方法就是将Get*函数转化为const类型的函数
在对应函数后面加上const关键字
class Point3d { public: Point3d(float x=0.0,float y=0.0,float z=0.0) :_x(x),_y(y),_z(z) { } float GetX() const{return _x;} float GetY() const{return _y;} float GetZ() const{return _z;} private: float _x,_y,_z; }; inline ostream& operator<<(ostream&out,const Point3d& pd) { out<<pd.GetX()<<" "<<pd.GetY()<<" "<<pd.GetZ()<<endl; return out; }
因此书《深度探索C++对象模型》第一章关于对象模型 P2页举得例子有问题的。它的代码是上面出错的代码。
相关文章推荐
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’的解决办法
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’的解决办法
- The resolution of ERROR C2662: cannot convert 'this' pointer from "const Class-Type" to "Class&"
- cannot convert 'this' pointer from 'const class Rational' to 'class Rational &' 是什么意思
- From an inner class, "this" points to the inner object. How do I get a "this" pointer to the enclosing object?
- System error &H80004015 - This class is configured to run as a security id different from the caller.
- find_if 仿函数错误:cannot convert 'this' pointer from 'const CActTaskData' to 'CActTaskData &'
- no known conversion for argument 1 from ‘[some_class]' to ‘[some_class]&’ 传const引用而非引用
- message from server: "Host is not allowed to connect to this MySQL server"解决办法
- vs2008下cannot convert parameter 1 from 'LPCTSTR' to 'const char *'的解决方法
- iOS开发 - "Cast from pointer to smaller type 'int' loses information” 解决办法
- Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key
- Incompatible pointer types assigning to 'NSMutableArray *' from 'NSArray *'
- error C2440: 'static_cast' : cannot convert from 'void (__thiscall CMainFrame::* )(void)' to 'LRESU
- invalid conversion from 'const char*' to 'char*'