Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
来源:互联网 发布:软件开发部规章制度 编辑:程序博客网 时间:2024/05/18 13:30
- 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 &' 是什么意思
- 关于C++ error C2662 cannot convert 'this' pointer from...
- cannot convert 'this' pointer from 'const cl
- find_if 仿函数错误:cannot convert 'this' pointer from 'const CActTaskData' to 'CActTaskData &'
- cannot convert parameter 1 from 'class A' to 'class A'
- cannot convert parameter from 'class CStdioFile' to 'class CStdioFile'
- 错误:Type mismatch: cannot convert from Class<SpringJUnit4ClassRunner> to Class<? extends Runner>
- Type mismatch: cannot convert from Class<SpringJUnit4ClassRunner> to Class<? extends Runner>
- Cannot convert from 'const char [..]' to 'LPCTSTR'
- Cannot convert from 'const char [..]' to 'LPCTSTR'
- ASP.NET MVC - 漫谈ActionMethodDispatcher
- 關于在WIN32調用一些Zw系列的文件操作函數.
- IOS学习笔记20—UIActivityIndicatorView、UIProgressView
- 实例repeater 分页、表头不动、添加列序号、日期分隔符转换(datareader存储过程实现)
- How to: Debug a Release Build (vs2010级以上版本Release下调试设置)
- Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’
- PCI配置空间简介
- iphone 开发中 拨打电话等的操作
- Objective-C新特性
- iOS:NSUserDefaults
- 插入排序
- Android多媒体应用开发-控制摄像头拍照
- SQL语句导EXCEL到数据库
- POJ 2502 Dijkstra