Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’的解决办法
作者:朱金灿
来源:http://www.cnblogs.com/clever101
下面的一段代码:
#include "stdafx.h"
#include <iostream>
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;}
inline std::ostream& operator<<(std::ostream&out)const
{
out<<GetX()<<" "<<GetY()<<" "<<GetZ()<<std::endl;
return out;
}
private:
float _x,_y,_z;
};
#include <iostream>
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;}
inline std::ostream& operator<<(std::ostream&out)const
{
out<<GetX()<<" "<<GetY()<<" "<<GetZ()<<std::endl;
return out;
}
private:
float _x,_y,_z;
};
VS C++2005编译出现下面错误:
1>d:\algorithmic\searchnum\console\console.cpp(21) : error C2662: “Point3d::GetX”: 不能将“this”指针从“const Point3d”转换为“Point3d &”
1> 转换丢失限定符
1>d:\algorithmic\searchnum\console\console.cpp(21) : error C2662: “Point3d::GetY”: 不能将“this”指针从“const Point3d”转换为“Point3d &”
1> 转换丢失限定符
1>d:\algorithmic\searchnum\console\console.cpp(21) : error C2662: “Point3d::GetZ”: 不能将“this”指针从“const Point3d”转换为“Point3d &”
原因在于带const修饰符的接口会把this指针转化为为const this类型。网上一种解决办法是,把需要调用的非const接口都改为const,如上例的GetX、GetY和GetZ函数改为:
float GetX() const{return _x;}
float GetY() const{return _y;}
float GetZ() const{return _z;}
float GetY() const{return _y;}
float GetZ() const{return _z;}
我想到的一种办法是可以直接在内部将const修饰符去掉,具体如下:
out<<(const_cast<Point3d*>(this))->GetX()<<" "<<(const_cast<Point3d*>(this))->GetY()<<" "<<(const_cast<Point3d*>(this))->GetZ()<<std::endl;
参考文献:
1. Error C2662, cannot convert ‘this’ pointer from ‘const class ’ to ‘class &’