运算符+(向量)的点 - 但矢量使用点,它是未声明的点声明 [英] Operator +(Vector) for Point - but the Vector uses Point and it's undeclared in Point declaration

查看:123
本文介绍了运算符+(向量)的点 - 但矢量使用点,它是未声明的点声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码:

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创建和运算符+向量:

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

但是当我把那个操作放在Point3D类声明的时候,没有在这里声明的Vector3D。我不能在Point3D之前移动Vector3D声明,因为它使用Point3D。

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.

推荐答案

定义 Vector3D ,只需在类定义中声明函数。这需要声明 Vector3D ,但不是完整的定义。

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

这篇关于运算符+(向量)的点 - 但矢量使用点,它是未声明的点声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆