C++ 操作员+;(向量)用于点-但向量使用点及其';未在点声明中声明

C++ 操作员+;(向量)用于点-但向量使用点及其';未在点声明中声明,c++,declaration,operator-keyword,C++,Declaration,Operator Keyword,我有密码: 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

我有密码:

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;
}

但当我把那个操作放在IDE Point3D类声明中时,我得到了一个错误,因为我没有在这里声明Vector3D。我不能将Vector3D声明移到Point3D之前,因为它使用Point3D。

将其放在类之外:

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

}

并且永远不要返回
对局部变量的引用

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

Andrew的答案可能是最好的选择,但是由于
操作符+
正在引用,您可以使用向前声明,然后在
Point3D
中声明
操作符+
,并在
Vector3D
下面定义它。在这种情况下,您还必须将其声明为
朋友
,然后向前声明
Vector3D
。@MikeSeymour:如果在两个类之后都放了向前声明,则不需要向前声明。您需要向前声明
friend
声明,该声明必须放在类定义中;除非扩展公共接口以访问坐标。