今天在写程序时遇到了一个报错:
error C2662: 'x' : cannot convert 'this' pointer from 'const class Point3d' to 'class Point3d &'
先看下代码:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class Point3d
{
public:
Point3d(int x = 0, int y = 0, int z = 0):m_x(x), m_y(y), m_z(z){}
public:
int x() {return m_x;}
int y() {return m_y;}
int z() {return m_z;}
void X(int x){m_x = x;}
void Y(int y){m_y = y;}
void Z(int z){m_z = z;}
private:
int m_x;
int m_y;
int m_z;
};
inline ostream& operator<<(ostream &os, const Point3d &pd)
{
return os << " m_x: " << pd.x() << " m_y: " << pd.y() << " m_z: " << pd.z();
}
报错点是标红的这一行,分析了半天,找不到问题的原因.
然后回到报错信息的提示,看看能不能找到些许的蛛丝马迹:无法将this指针从const引用类对象类型转换为类对象类型,再把这个错误翻译一下:就是报错的原因在于我们将一个const this指针转换为一个非const导致的错误。
那么这是为什么呢?回到代码,我们在重载<<函数中声名的第二个参数是一个const Point3d& 类对象的引用,而在函数实现内部,我们用其调用类的成员方法x(),这里发生了什么?没错,这里编译器隐含了一个const this指针传给了类成员函数x(),而在类的实现中这个成员函数是非const的,这个函数的隐含this指针参数是非const的.换句换说,这个函数形参与实参结合时,发生了const 指针到非const指针的转换,因此报错!!!
知道了报错原因,我们把类的这些成员函数声明为const,函数声明为const,隐含的this指针也变成了const,于是这个问题应该不会再发生了
// C++中实现
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class Point3d
{
public:
Point3d(int x = 0, int y = 0, int z = 0):m_x(x), m_y(y), m_z(z){}
public:
int x() const{return m_x;}
int y() const{return m_y;}
int z() const{return m_z;}
void X(int x){m_x = x;}
void Y(int y){m_y = y;}
void Z(int z){m_z = z;}
// inline ostream& operator<<(ostream &os/*, const Point3d& pd*/)
/* {
return os << " m_x: " << this->X() << " m_y: " << this->Y() << " m_z: " << this->Z();
}*/
private:
int m_x;
int m_y;
int m_z;
};
inline ostream& operator<<(ostream &os, const Point3d &pd)
{
return os << " m_x: " << pd.x() << " m_y: " << pd.y() << " m_z: " << pd.z();
}
重新编译,Ok!!!
编译环境:VC++6.0