运算符 +(Vector) 表示点 - 但向量使用点,并且在点声明中未声明



我有代码:

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 创建和运算符 +,它将采用一个向量:

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。而且我不能在Point3D之前移动Vector3D声明,因为它使用Point3D。

把它放在类之外:

Point3D operator+(const Point3D &p, const Vector3D &v)
{
}

也不会回来a reference to local variable了!

你可以

通过将函数定义移动到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 {
    // ...
}

最新更新