第八週項目1----複數類中的運算符重載(1)

/*
 *Copyright  (c)  2014,煙臺大學計算機學院
 *All rights reserved.
 *文件名稱: test.cpp
 *作者: 郭棟
 *完成日期:2015年 4月 29日
 *版本號:v1.0
 *問題描述:用類的成員函數,定義複數類重載運算符+、-、*、/,使之能用於複數的加減乘除
 *輸入描述:
 *程序輸出
 */



#include <iostream>

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);
    Complex operator-(const Complex &c2);
    Complex operator*(const Complex &c2);
    Complex operator/(const Complex &c2);
    void display();
private:
    double real;
    double imag;
};

   Complex Complex:: operator+(const Complex &c2)
    {
        Complex c;
        c.real=this->real+c2.real ;
        c.imag=this->imag+c2.imag;
        return c;
    }
     Complex Complex:: operator-(const Complex &c2)
    {
       Complex c;
        c.real=this->real-c2.real ;
        c.imag=this->imag-c2.imag;
        return c;
    }
     Complex Complex:: operator*(const Complex &c2)
    {
        Complex c;
        c.real=this->real*c2.real ;
        c.imag=this->imag*c2.imag;
        return c;
    }
     Complex Complex:: operator/(const Complex &c2)
    {
        Complex c;
        c.real=this->real/c2.real ;
        c.imag=this->imag/c2.imag;
        return c;
    }
void Complex::display()
{
    cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
//下面定義用於測試的main()函數
int main()
{
    Complex c1(3,4),c2(5,-10),c3;
    cout<<"c1=";
    c1.display();
    cout<<"c2=";
    c2.display();
    c3=c1+c2;
    cout<<"c1+c2=";
    c3.display();
    c3=c1-c2;
    cout<<"c1-c2=";
    c3.display();
    c3=c1*c2;
    cout<<"c1*c2=";
    c3.display();
    c3=c1/c2;
    cout<<"c1/c2=";
    c3.display();
    return 0;
}

運行結果:


總結:做倒是做出來了,但完全是使出來的,這不對改改,那不對改改,基礎知識不牢

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章