題目描述
定義一個複數類Complex,重載運算符“+”,使之能用於複數的加法運算。將運算符函數重載爲非成員、非友元的普通函數。編寫程序,求兩個複數之和。
輸入
兩個複數
輸出
複數之和
樣例輸入
3 4
5 -10
樣例輸出
(8.00,-6.00i)
解題代碼:
#include <iostream>
#include <iomanip>
using namespace std;
class Complex
{
public:
Complex()
{
real=0;
imag=0;
}
Complex(double r,double i) { real=r; imag=i; } Complex operator+(const Complex &c2);
double get_real();
double get_imag();
void display();
private:
double real;
double imag;
};
Complex Complex::operator+(const Complex &c2)
{
Complex c3;
c3.real=real+c2.real;
c3.imag=imag+c2.imag;
return c3;
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main()
{
double real,imag;
cin>>real>>imag;
Complex c1(real,imag);
cin>>real>>imag;
Complex c2(real,imag);
Complex c3=c1+c2;
cout<<setiosflags(ios::fixed);
cout<<setprecision(2);
c3.display();
return 0;
}