面向對象程序設計——函數重載運算符

定義complex類,它包含兩個雙精度型的數據成員real 和 imag 以及兩個構造函數:一個是無參函數,一個是有參數的函數。

要求:使用類的成員函數 或者友元函數重載運算符+、-、×、÷,使其能夠實現complex類對象的相應運算。

注(a+bi) ÷(c+di)=((ac+bd) ÷(c2+d2))+((bc-ad) ÷(c2+d2))i

 

#include<iostream>
#include<cmath>
using namespace std;

class Complex
{
public:
    double real;
    double imag;
    Complex(){real = 0, imag = 0;}
    Complex(double r, double i)
    {
        real = r;
        imag = i;
    }
    friend Complex operator+(Complex c1, Complex c2);
    friend Complex operator-(Complex c1, Complex c2);
    friend Complex operator*(Complex c1, Complex c2);
    friend Complex operator/(Complex c1, Complex c2);
    void display();
};
void Complex::display()
{
    cout << "(" << real << ")+(" << imag << ")i" << endl;
}
Complex operator+(Complex c1, Complex c2)
{
    Complex x;
    x.real = c1.real + c2.real;
    x.imag = c1.imag + c2.imag;
    return x;
}
Complex operator-(Complex c1, Complex c2)
{
    Complex x;
    x.real = c1.real - c2.real;
    x.imag = c1.imag - c2.imag;
    return x;
}
Complex operator*(Complex c1, Complex c2)
{
    Complex x;
    x.real = ((c1.real * c2.real) - (c1.imag * c2.imag));
    x.imag = ((c1.imag * c2.real) + (c1.real * c2.imag));
    return x;
}
Complex operator/(Complex c1, Complex c2)
{
    Complex x;
    x.real = (((c1.real * c2.real) + (c1.imag * c2.imag)) / ((c2.real * c2.real) + (c2.imag * c2.imag)));
    x.imag = (((c1.imag * c2.real) - (c1.real * c2.imag)) / ((c2.real * c2.real) + (c2.imag * c2.imag)));
    return x;
}
int main()
{
    Complex c1(3, 4), c2(5, -10), c3;

    c3 = c1 + c2;
    cout << "c1 + c2 = ";
    c3.display();
    cout << endl;

    c3 = c1 - c2;
    cout << "c1 - c2 = ";
    c3.display();
    cout << endl;

    c3 = c1 * c2;
    cout << "c1 * c2 = ";
    c3.display();
    cout << endl;

    c3 = c1 / c2;
    cout << "c1 / c2 = ";
    c3.display();
    cout << endl;
    return 0;
}

輸出結果:

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