在C++中覆盖=运算符

Aer*_*ero 1 c++ overriding

我试图覆盖=运算符,以便我可以将我的Point类更改为Vector3类.

Point tp = p2 - p1;
Vec3 v;
v = tp;
Run Code Online (Sandbox Code Playgroud)

我面临的问题是,"v"将使其x,y,z成员始终等于零.

Vec3.h:

Vec3 operator =(Point a) const;
Run Code Online (Sandbox Code Playgroud)

Vec3.cpp:

Vec3 Vec3::operator =(Point a) const
    {
        return Vec3(a.x,a.y,a.z);
    }
Run Code Online (Sandbox Code Playgroud)

再次感谢所有的帮助:)

Rus*_*ove 8

已经有一段时间了,但我想你想要

Vec3& Vec3::operator=(const Point &a) 
{
    x = a.x; y = a.y; z = a.z;

    return *this;  // Return a reference to myself.
}
Run Code Online (Sandbox Code Playgroud)

赋值修改'this',因此它不能是const.它不会返回新的Vec3,它会修改现有的Vec3.您可能还需要Point的复制构造函数,它也是如此.