複數類的運算符重載 運算符重載指對已有的運算符重新進行定義,賦予其另一種功能,以适應不同的資料類型 對于複數類,有實部和虛部兩部分,是以我們對于+,-,*,/,要列式計算。 如要加上+=,-+,*=,/=也會很容易。 程式如下:
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double real = 0.0, double image = 0.0); //聲明構造函數時指定預設參數
Complex& operator=(const Complex& c);
Complex operator+(const Complex& c);
Complex operator-(const Complex& c);
Complex operator*(const Complex& c);
Complex operator/(const Complex& c);
void display();
private:
double _real;
double _image;
};
//定義構造函數
Complex::Complex(double real, double image)
{
_real = real;
_image = image;
}
//複數指派
Complex& Complex::operator=(const Complex& c)
{
if (this != &c)
{
_real = c._real;
_image = c._image;
}
return *this;
}
//複數相加
Complex Complex::operator+(const Complex& c)
{
Complex c1;
c1._real = _real + c._real;
c1._image = _image + c._image;
return c1;
}
//複數相減
Complex Complex::operator-(const Complex& c)
{
Complex c1;
c1._real = _real - c._real;
c1._image = _image - c._image;
return c1;
}
//複數相乘(a+bi)*(c+di)
Complex Complex::operator*(const Complex& c)
{
Complex c1;
c1._real = _real*c._real - _image*c._image;
c1._image = _image*c._real + _real*c._image;
return c1;
}
//複數相除(a+bi)/(c+di)
Complex Complex::operator/(const Complex& c)
{
Complex c1;
c1._real = (_real*c._real + _image*c._image) / (c._real*c._real + c._image*c._image);
c1._image = (_image*c._real - _real*c._image) / (c._real*c._real + c._image*c._image);
return c1;
}
void Complex::display()
{
cout << "(" << _real << "," << _image << ")" << endl;
}
void test()
{
Complex c1(1.0, 2.0);
Complex c2(4.0, 5.0);
Complex c3;
c3 = c1.operator+(c2);
c3.display();
c3 = c1.operator-(c2);
c3.display();
c3 = c1.operator*(c2);
c3.display();
c3 = c1.operator/(c2);
c3.display();
c2 = c1.operator=(c1);
c2.display();
}
int main()
{
test();
system("pause");
return 0;
}
在此基礎上,就可以直接利用已重載好的運算符來重載+=,-=,*=,/= 程式如下:
//複數加等(a+bi)=(a+bi)+(c+di)
void Complex:: operator+=(const Complex& c)
{
*this=*this+c;
/*_real += c._real;
_image += c._image;*/
}
//複數減等(a+bi)=(a+bi)-(c+di)
void Complex:: operator-=(const Complex& c)
{
*this = *this - c;
/*_real -= c._real;
_image -= c._image;*/
}
//複數乘等(a+bi)=(a+bi)*(c+di)
void Complex:: operator*=(const Complex& c)
{
*this = *this*c;
}
//複數除等(a+bi)=(a+bi)/(c+di)
void Complex::operator/=(const Complex& c)
{
*this = *this / c;
}
void Complex::display()
{
cout << "(" << _real << "," << _image << ")" << endl;
}
void test2()
{
Complex c1(1.0, 2.0);
Complex c2(4.0, 5.0);
c1+=c2;
c1.display();
c1-=(c2);
c1.display();
c1*=(c2);
c1.display();
c1/=(c2);
c1.display();
}
運作結果如下,讀者可自行驗證。
