我有代码:
class Point3D{
protected:
float x;
float y;
float z;
public:
Point3D(){x=0; y=0; z=0;}
Point3D(const Point3D & point){x = point.x; y = point.y; z = point.z;}
Point3D(float _x,float _y,float _z){x = _x; y = _y; z = _z;}
}
class Vector3D{
protected:
Point3D start;
Point3D end;
public:
...
Point3D getSizes(){
return Point3D(end-start);
}
}我想为Point3D创建一个带向量的operator+:
Point3D & operator+(const Vector3D &vector){
Point3D temp;
temp.x = x + vector.getSizes().x;
temp.y = y + vector.getSizes().y;
temp.z = z + vector.getSizes().z;
return temp;
}但是当我把这个操作放在Point3D类声明中时,我得到了错误,因为我没有在这里声明Vector3D。而且我不能将Vector3D声明移到Point3D之前,因为它使用了Point3D。
发布于 2012-07-02 21:07:03
您可以通过将函数定义移到Vector3D的定义之后来解决这个问题,只需在类定义中声明函数即可。这需要声明Vector3D,但不需要完整的定义。
此外,永远不要返回对局部自动变量的引用。
// class declaration
class Vector3D;
// class declaration and definition
class Point3D {
// ...
// function declaration (only needs class declarations)
Point3D operator+(const Vector3D &) const;
};
// class definition
class Vector3D {
// ...
};
// function definition (needs class definitions)
inline Point3D Point3D::operator+(const Vector3D &vector) const {
// ...
}发布于 2012-07-02 20:47:20
将其放在类之外:
Point3D operator+(const Point3D &p, const Vector3D &v)
{
}而且永远不会返回a reference to local variable!
https://stackoverflow.com/questions/11293969
复制相似问题