设为首页 加入收藏

TOP

C++复数运算 重载
2015-02-02 15:48:45 来源: 作者: 【 】 浏览:19
Tags:复数 运算 重载

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


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


#include
/*
#include
#include
#include
#include
#include
*/
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<? ? if (imag)
? ? {
? ? ? ? cout.setf(ios::showpos);
? ? ? ? cout<? ? }
? ? cout<? ? 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;
}


C语言梳理一下,分布在以下10个章节中:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇详细理解“>/dev/null 2>&1.. 下一篇使用 Swift 构建一个 iOS 的邮件..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: