C++复数运算 重载

近期整理下很久前写的程序,这里就把它放在博文中了,有些比较简单,但是很有学习价值。  


 下面就是自己很久前实现的复数重载代码,这里没有考虑特殊情况,像除法中,分母不为零情况。

#include <iostream>
/*
#include <conio.h>
#include<stdio.h>
#include<iomanip>
#include<string>
#include<sstream>
*/
using namespace std;

class complex
{
    double real,imag;
public:
    complex(double,double);
    void disp(char *);
    friend complex operator + (complex,complex);
    friend complex operator - (complex,complex);
    friend complex operator * (complex,complex);
    friend complex operator / (complex,complex);
};

complex::complex (double r=0,double i=0)
{
    real = r;
    imag = i;
}

void complex::disp (char *str)
{
    cout.unsetf(ios::showpos);
    cout<<str<<"="<<real;
    if (imag)
    {
        cout.setf(ios::showpos);
        cout<<imag<<'i';
    }
    cout<<endl;
    cout.unsetf(ios::showpos);
}

complex operator + (complex cpl1,complex cpl2)
{
    double t=cpl1.real+cpl2.real;
    double i=cpl1.imag+cpl2.imag;
    return complex(t,i);
}

complex operator - (complex cpl1,complex cpl2)
{
    double t=cpl1.real-cpl2.real;
    double i=cpl1.imag-cpl2.imag;
    return complex(t,i);
}

complex operator * (complex cpl1,complex cpl2)
{
    double t=cpl1.real*cpl2.real - cpl1.imag*cpl2.imag;
    double i=cpl1.real*cpl2.imag + cpl1.imag*cpl2.real;
    return complex(t,i);
}

complex operator / (complex cpl1,complex cpl2)
{
    double t=(cpl1.real*cpl2.real+cpl1.imag*cpl2.imag)/(cpl2.real*cpl2.real+cpl2.imag*cpl2.imag);
    double i=(cpl1.imag*cpl2.real-cpl1.real*cpl2.imag)/(cpl2.real*cpl2.real+cpl2.imag*cpl2.imag);
    return complex(t,i);
}

int main(void)
{
    complex c1(25,40),c2(100,200),c3(0);
    c1.disp("c1");
    c2.disp("c2");
    c3=c1+c2;
    c3.disp("c3");
    c3=c1-c3;
    c3.disp("c3");
    c3=c1*c2;
    c3.disp("c3");
    c3=c1/c2;
    c3.disp("c3");
    getchar();
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值