c++ - 在 C++ 中重写 = 运算符

标签 c++ overriding

我正在尝试覆盖 = 运算符,以便我可以将我的 Point 类更改为 Vector3 类。

Point tp = p2 - p1;
Vec3 v;
v = tp;

我面临的问题是,“v”的 x、y、z 成员始终为零。

Vec3.h:

Vec3 operator =(Point a) const;

Vec3.cpp:

Vec3 Vec3::operator =(Point a) const
    {
        return Vec3(a.x,a.y,a.z);
    }

再次感谢所有的帮助:)

最佳答案

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

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

    return *this;  // Return a reference to myself.
}

赋值修改'this',所以它不能是const。它不会返回新的 Vec3,它会修改现有的 Vec3。您可能还需要 Point 的复制构造函数,它的作用相同。

关于c++ - 在 C++ 中重写 = 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3973057/

相关文章:

c++ - 错误 C2011 : 'member' : 'struct' type redefinition on moving a struct to a new header file

c++ - 在 Windows 的 Eclipse C++ 中运行 Hello World 应用程序

c# - 为什么 C#/CLR 不支持方法重写协方差/反方差?

c++ - 为什么我不能将 unique_ptr 转换为赋值中的原始指针?

c++ - 法线贴图和平移扰乱了我的照明

C++在尝试覆盖方法时无法实例化抽象类

actionscript-3 - 覆盖继承的 getter/setter

jquery - 重写 JavascriptConfirm() 同时保留回调

c++ - 如何将C makefile项目导入eclipse或放在eclipse下

Java - 比较父类对象的子属性