1. 程式人生 > >第十五週oj刷題——Problem J: C++習題 複數類--過載運算子+

第十五週oj刷題——Problem J: C++習題 複數類--過載運算子+

Description

定義一個複數類Complex,過載運算子“+”,使之能用於複數的加法運算。將運算子函式過載為非成員、非友元的普通函式。編寫程式,求兩個複數之和。

Input

兩個複數

Output

複數之和

Sample Input

3 4
5 -10

Sample Output

(8.00,-6.00i)
/* All rights reserved.
 * 檔名稱:test.cpp
 * 作者:陳丹妮
 * 完成日期:2015年 6 月 21 日
 * 版 本 號:v1.0
 */
#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(){}
Complex::Complex(double r,double i)
{
    real=r;
    imag=i;
}
double Complex::get_imag()
{
    return imag;
}Complex::Complex(){}
Complex::Complex(double r,double i)
{
    real=r;
    imag=i;
}
double Complex::get_imag()
{
    return imag;
}
double Complex::get_real()
{
    return real;
}
Complex operator +(Complex&c1,Complex&c2)
{
    return Complex(c1.get_real()+c2.get_real(),c1.get_imag()+c2.get_imag());
}
void Complex::display()
{
    cout<<"("<<real<<","<<imag<<"i)"<<endl;
}

double Complex::get_real()
{
    return real;
}
Complex operator +(Complex&c1,Complex&c2)
{
    return Complex(c1.get_real()+c2.get_real(),c1.get_imag()+c2.get_imag());
}
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;
}

學習心得:const 不能隨便亂用啊,需要的都要定義,不要嫌麻煩,學習不能嫌麻煩,有會了一個知識點好開心啊!!!