題目要求如下:
-----------------------------------------------------------------------------------------------------------------------------------------------
代碼如下:
/*
* Copyright (c) 2013, 煙臺大學計算機學院
* All rights reserved.
* 作 者: 沈遠宏
* 完成日期:2014 年06月24日
* 版 本 號:v1.0
* 問題描述:Description
定義一個複數類Complex,重載運算符“+”,使之能用於複數的加法運算。將運算符函數重載爲非成員、非友元的普通函數。編寫程序,求兩個複數之和。
Input
兩個複數
Output
複數之和
*/
//前置代碼及類型定義已給定如下,提交時不需要包含,會自動添加到程序前部
#include <iostream>
#include <iomanip>
using namespace std;
class Complex
{
public:
Complex();
Complex(double r,double i);
double get_real();
double get_imag();
void display();
private:
double real;
double imag;
};
Complex::Complex(double r,double i):real(r),imag(i) {}
double Complex::get_real()
{
return real;
}
double Complex::get_imag ()
{
return imag;
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
Complex operator + (Complex& c1,Complex& c2)
{
return Complex(c1.get_real()+c2.get_real(),c1.get_imag()+c2.get_imag());
}
//主函數已給定如下,提交時不需要包含,會自動添加到程序尾部
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;
}
運行結果:
OJ要求結果輸出例樣: