#include<iostream>
using namespace std;
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
friend Complex operator+(Complex &c1,Complex &c2);
friend Complex operator-(Complex &c1,Complex &c2);
friend Complex operator*(Complex &c1,Complex &c2);
friend Complex operator/(Complex &c1,Complex &c2);
friend ostream& operator<<(ostream&,Complex&c);
friend istream& operator>>(istream&,Complex&c);
void display();
private:
double real;
double imag;
};
Complex operator+(Complex &c1,Complex &c2)
{
Complex c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c;
}
Complex operator-(Complex &c1,Complex &c2)
{
Complex c;
c.real=c1.real-c2.real;
c.imag=c1.imag-c2.imag;
return c;
}
Complex operator*(Complex &c1,Complex &c2)
{
Complex c;
c.real=c1.real*c2.real+c1.imag*c2.imag;
c.imag=c2.real*c1.imag+c2.imag*c1.real;
return c;
}
ostream& operator<<(ostream&,Complex&c)
{
cout<<"(";
cout<<c.real<<"+";
cout<<c.imag<<"i)"<<endl;
return cout;
}
istream& operator>>(istream&,Complex&c)
{
cin>>c.real>>c.imag;
return cin;
}
//下面是测试函数
int main()
{
Complex c1,c2,c3;
cout<<"c1="<<c1;
cout<<"c2="<<c2;
c3=c1+c2;
operator+(c1,c2);
cout<<"c1+c2="<<c3;
c3=c1-c2;
cout<<"c1-c2="<<c3;
c3=c1*c2;
cout<<"c1*c2="<<c3;
return 0;
}
第九周任务二
最新推荐文章于 2024-01-25 00:15:00 发布
本文介绍了一个使用C++实现的复数类,该类支持基本的复数运算,包括加法、减法、乘法,并通过运算符重载简化了这些操作。文中还展示了如何使用输入输出流来读取和显示复数。
6445

被折叠的 条评论
为什么被折叠?



