首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >2操作符超载有什么区别?

2操作符超载有什么区别?
EN

Stack Overflow用户
提问于 2015-11-09 15:31:10
回答 1查看 64关注 0票数 0
代码语言:javascript
复制
#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; }

你能告诉我复形operator*=(配合物b)和复形&operator+=(配合物b)的区别吗?

非常感谢你!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-09 15:43:43

operator*=的实现是不正确的。它所做的事情与operator+=相同。此外,它返回一个副本而不是一个引用。

更好的执行办法是:

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33612541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档