/*
Output
两个虚数相加的结果,格式(a,bi)形式
Sample Input
2.5 3.1 -4.5 0.3
Sample Output
(-2,3.4i)
*/
#include<iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real=0;imag=0;
}
Complex(double r,double i)
{
real=r;
imag=i;
}
Complex operator+(Complex &c2);
//friend ostream & operator<<(ostream&,Complex&);
void display();
//声明需要的成员或友元函数,包括构造函数、用于重载运算符的函数及用于显示结果的函数
private:
double real;
double imag;
};
Complex Complex::operator+(Complex &c2)
{
return Complex(real+c2.real,imag+c2.imag);
}
/*ostream & operator<<(ostream &output,Complex &c)
{
output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;
return output;
}*/
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
//下面定义成员函数
//下面用main()函数测试,完成输入输出
int main()
{
double cr1, ci1, cr2, ci2;
cin>>cr1>>ci1>>cr2>>ci2;
Complex c1(cr1, ci1),c2(cr2, ci2),c3;
c3=c1+c2;
c3.display();
return 0;
}
运算符重载
最新推荐文章于 2024-09-09 21:20:50 发布