- 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页举得例子有问题的。它的代码是上面出错的代码。