我正在尝试覆盖 = 运算符,以便我可以将我的 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/