首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >操作符+( Vector ) for Point -但Vector使用Point,并且它在Point声明中未声明

操作符+( Vector ) for Point -但Vector使用Point,并且它在Point声明中未声明
EN

Stack Overflow用户
提问于 2012-07-02 20:45:42
回答 2查看 180关注 0票数 2

我有代码:

代码语言:javascript
复制
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+:

代码语言:javascript
复制
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。而且我不能将Vector3D声明移到Point3D之前,因为它使用了Point3D。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-02 21:07:03

您可以通过将函数定义移到Vector3D的定义之后来解决这个问题,只需在类定义中声明函数即可。这需要声明Vector3D,但不需要完整的定义。

此外,永远不要返回对局部自动变量的引用。

代码语言:javascript
复制
// 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 {
    // ...
}
票数 3
EN

Stack Overflow用户

发布于 2012-07-02 20:47:20

将其放在类之外:

代码语言:javascript
复制
Point3D operator+(const Point3D &p, const Vector3D &v)
{

}

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11293969

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档