复数运算符的重载与模版类complex的对比

#include <iostream>
#include "operatorOverload.h"
#include<complex>
using namespace std;


int main()
{
    Complex c1(1,2),c2(4,-5),c3,c4,c5;
    c3 = c1+c2;
    c4 = c1*c2;
    c5 = c1/c2;
    c3.print();
    c4.print();
    c5.print();


    complex<double> d1(1,2),d2(4,-5),d3,d4,d5;
    d3=d1+d2;
    d4=d1*d2;
    d5=d1/d2;
    cout<<"d3="<<d3.real()<<" "<<d3.imag()<<endl;
    cout<<"d4="<<d4.real()<<" "<<d4.imag()<<endl;
    cout<<"d5="<<d5.real()<<" "<<d5.imag()<<endl;
    return 0;

}


//.h文件

#include<string>
#include<string.h>
#include<iostream>
using namespace std;
class Complex
{
    public:
    Complex(double r= 0,double i = 0)
    {
        real = r;
        image = i;
       // cout <<"构造函数被调用"<<endl;
    }
    void print()
    {
        if(image >0) cout<<real <<"+" <<image<<"i"<<endl;
        else if(image <0) cout <<real <<image<<"i"<<endl;
        else cout <<real;
    }
    Complex operator*(const Complex &c);
    friend Complex operator + (const Complex &c1,const Complex &c2);
    friend Complex operator / (const Complex &c1,const Complex &c2);
private :
    double real,image;
};
Complex operator /(const Complex &c1,const Complex &c2)
{
    Complex c3;
    double a,b,c,d;
    a = c1.real;b = c1.image;c = c2.real; d = c2.image;
    c3.real = (a*c + b*d)/(c*c+d*d);
    c3.image = (b*c - a*d)/(c*c+d*d);
    return c3;


}
Complex operator+(const Complex &c1,const Complex &c2)
{
    Complex c3;
    c3.real = c1.real+c2.real;
    c3.image = c1.image +c2.image;


    return c3;
}
Complex Complex ::operator *(const Complex &c)
{
    Complex c3;
    c3.real = real * c.real - image *c.image;
    c3.image = real * c.image + image * c.real;
    return c3;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值