Operator +(Vector) for Point - but the Vector uses Point and it's undeclared in Point declaration

蹲街弑〆低调 提交于 2019-12-24 00:48:23

问题


I have the code:

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

I want to create and operator+ for Point3D that will take an vector:

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

But when I put that operation iside Point3D class declaration, I got error because I don't have Vector3D declared here. And I cannot move Vector3D declaration before Point3D, because it uses Point3D.


回答1:


You can solve this by moving the function definition after the definition of Vector3D, and just declare the function in the class definition. This requires a declaration of Vector3D, but not the full definition.

Also, never return a reference to a local automatic variable.

// 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 {
    // ...
}



回答2:


put it outside classes:

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

}

And never ever ever return a reference to local variable!



来源:https://stackoverflow.com/questions/11293969/operator-vector-for-point-but-the-vector-uses-point-and-its-undeclared-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!