c++ - 2 运算符重载有什么区别?

标签 c++

#include<iostream>
using namespace std;
#include<math.h>
class complex {
    float real, image;
public:
    complex(float r = 0, float i = 0)
    {
        real = r; image = i;
    }

    complex & operator+=(complex b)
    {
        real += b.real;
        image += b.image;
        return *this;
    }
    complex  operator*=(complex b)
    {
        real += b.real;
        image += b.image;
        return *this;
    }
    void display()
    {
        cout << real << (image >= 0 ? '+' : '-') << "j*" << fabs(image) << endl;
    }
};
int main() {    return 0; }

你能告诉我复数运算符*=(复数b)的区别吗 和复数 & operator+=(复数 b)

非常感谢!

最佳答案

operator*= 的实现不正确。它与 operator+= 的作用相同。此外,它返回一个拷贝而不是一个引用。

更好的实现方式是:

complex& operator*=(complex b)
{
   double tempReal = real*b.real - image*b.image;
   double tempImage = real*b.image + image*b.real; 
   real = tempReal;
   image = tempImage;
   return *this;
}

关于c++ - 2 运算符重载有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612541/

相关文章:

c++ - setsockopt 返回错误 10014

c++ - 无法打开包含文件 : 'QWebView' : No such file or directory

c++ - Windows 10下Winhttp SSL的问题

android libuv 使用未声明的标识符 'EPOLL_CLOEXEC'

c++ - 如何使用tinycthread做C++并发编程

C++ 不能在 cout 中使用 vector 和字符串文字

c++ - 模板化转换运算符优先级

c++ - Glew 和 Glut 如何激活像素格式?

android - 来自 Android 的 OpenCV JNI 上的 SIGSEGV

c++ - 将 float 转换为 int,有和没有转换