#include<iostream>
using namespace std;
class Complex{
private:
float real;
float image;
public:
Complex()
{
}
Complex(float r,float i)
{
real = r;
image = i;
}
//友元:
friend istream& operator>>(istream& is,Complex& c);
friend ostream& operator<<(ostream& os,Complex c);
Complex operator+(Complex c)
{
Complex c1;
c1.real = real+c.real;
c1.image = image+c.image;
return c1;
}
};
istream& operator>>(istream& is,Complex& c)
{
cin>>c.real>>c.image;
return is;
}
ostream& operator<<(ostream& os,Complex c)
{
if(c.image>0)
{
cout<<c.real<<"+"<<c.image<<"i"<<endl;
}
else if(c.image<0)
{
cout<<c.real<<c.image<<"i"<<endl;
}
else
{
cout<<c.real<<endl;
}
}
int main()
{
Complex c1,c2,c3;
cin>>c1>>c2;
cout<<c1<<c2;
c3=c1+c2;
cout<<c3;
return 0;
}
C++(定义Complex复数类,实现相加的功能)
最新推荐文章于 2023-04-05 11:12:13 发布