【问题标题】:Operator +(Vector) for Point - but the Vector uses Point and it's undeclared in Point declaration运算符 +(Vector) 用于 Point - 但 Vector 使用 Point 并且在 Point 声明中未声明
【发布时间】:2012-07-02 12:45:41
【问题描述】:

我有代码:

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

【问题讨论】:

标签: c++ declaration operator-keyword


【解决方案1】:

把它放在课外:

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

}

并且永远不会返回a reference to local variable

【讨论】:

  • 在这种情况下,您还必须将其声明为 friend,并转发声明 Vector3D 才能做到这一点。
  • @MikeSeymour:如果你把它放在两个类之后,就不需要前向声明
  • 你需要friend声明的前向声明,必须放在类定义中;除非扩展公共接口以提供对坐标的访问权限。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2022-12-28
    • 1970-01-01
    相关资源
    最近更新 更多