c++ - 运算符重载。 q = q1+q2,q1 被修改,但我希望 q1 和 q2 保持不变

标签 c++ visual-studio-2012 operator-overloading

我大约在 1 或 2 周前学习了运算符重载,我想我知道它是如何工作的,但我正在尝试重载运算符 + 以便它返回一个新的 CCuaternion 效果很好,但是

CCuaternion(float w, float x, float y, float z) {
    this->w = w;
    this->x = x;
    this->y = y;
    this->z = z;
} //Ccuaternion constructor at Ccuaternion.h

CCuaternion operator + (CCuaternion &q2); // at CCuaternion.h

CCuaternion CCuaternion::operator + (CCuaternion &q2){ // at Ccuaternion.cpp
CCuaternion suma;

suma.setW(w += q2.getW());
suma.setX(x += q2.getX());
suma.setY(y += q2.getY());
suma.setZ(z += q2.getZ());

return suma; }

在我的 main 中,我有一个名为 qsuma 的对象 CCuaternion,它接收重载返回的 CCuaternion .它看起来像这样:

q1 = CCuaternion(0, 1, 0, 1); // at main.cpp
q2 = CCuaternion(1, 0, 0, 1);

qsuma = (q1+q2);

正如预期的那样,qsuma 以值 1, 1, 0, 2 结束。 q2 保持不变,但 q1 最终的值与 qsuma 相同。

最佳答案

重载加法运算符的首选方式是这样的:

CCuaternion & CCuaternion::operator += (CCuaternion const &q2)
{
    w += q2.w;
    x += q2.x;
    y += q2.y;
    z += q2.z;

    return *this;
}

这是一个非成员函数:

CCuaternion operator + (CCuaternion q1, CCuaternion const &q2)
{
    return q1 += q2;
}

这使您的代码非常简单和直观,还可以让人们在您的类(class)中使用 +=

关于c++ - 运算符重载。 q = q1+q2,q1 被修改,但我希望 q1 和 q2 保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909941/

相关文章:

c++ - 这个 lambda 的参数是什么类型?

c++ - unsigned int 和 unsigned long 都是 32 位的,但我不能在不强制转换的情况下混合使用它们……为什么?

c++ - 我可以对 2 个外观相似的类使用类型转换运算符吗?

ios - 在 Swift 中使用自定义运算符优于方法的优势

c++ - 模板类 + 运算符 + friend = Unresolved external

c++ - Emacs 自动完成功能无法正常工作

c++ - 按类型比较指针?

c++ - 如何将 char 数组放入 std::string

visual-studio - Notepad++的ASP.NET Razor语法突出显示

visual-studio-2010 - 是否可以使用 VS 2010 远程调试 Windows 8?