定義複數類Complex,包括兩個double型的數據成員real和image,要求對+、-、、/、+=、-+、=、/=、幾個運算符進行重載以實現複數的運算,並進行驗證。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Complex
{
public:
//默認的構造函數(含缺省值,並初始化參數)
Complex(const double real = 0.0, const double image = 0.0)
:_real(real) //初始化
, _image(image)
{}
//拷貝構造函數
Complex(const Complex& c)
{
_real = c._real;
_image = c._image;
}
//析構函數
~Complex()
{}
//賦值運算符的重載
Complex& operator=(const Complex& c)
{
this->_real = c._real;
//_real = c._real;//隱含的this指針
this->_image = c._image;
//_image = c._image;
return *this;
}
//加法運算符的重載
Complex operator+(const Complex& c)
{
Complex tmp;
tmp._real = _real + c._real;
tmp._image = _image + c._image;
return tmp;
}
//減法
Complex operator-(const Complex& c)
{
Complex tmp;
tmp._real = _real - c._real;
tmp._image = _image - c._image;
return tmp;
}
//乘法
Complex operator*(const Complex& c)
{
Complex tmp;
tmp._real = _real * c._real - _image*c._image;
tmp._image = _real * c._image + _image*c._real;
return tmp;
}
//除法
Complex operator/(const Complex& c)
{
Complex tmp;
tmp._real = (_real / c._real + _image*c._image) / (c._real*c._real + c._image*c._image);
tmp._image = (_image*c._real - _real*c._image) / (c._real*c._real + c._image*c._image);
return tmp;
}
Complex operator+=(const Complex& c)
{
_real += c._real;
_image += c._image;
return *this;
}
Complex operator-=(const Complex& c)
{
_real -= c._real;
_image -= c._image;
return *this;//返回當前對象
}
Complex operator*=(const Complex& c)
{
double real0 = _real;
double image0 = _image;
_real = (real0 * c._real - image0*c._image);
_image = (real0 * c._image + image0*c._real);
return *this;
}
Complex operator/=(const Complex& c)
{
double real0 = _real;
double image0 = _image;
_real /= (real0 / c._real + image0*c._image) / (c._real*c._real + c._image*c._image);
_image /= (image0*c._real - real0*c._image) / (c._real*c._real + c._image*c._image);
return *this;
}
void Display()
{
cout << _real << " " << _image << endl;
}
private:
double _real;
double _image;
};
//測試函數
void Funtest1()
{
Complex c1(2.0, 3.0);
c1.Display();
Complex c2(c1);
c2.Display();
Complex c3;
c3 = c1+c2;
c3.Display();
}
void Funtest2()
{
Complex c1(2.0, 3.0);
c1.Display();
Complex c2(c1);
c2.Display();
c1 *= c2;
c1.Display();
}
int main()
{
cout << "Funtest1:" << endl;
Funtest1();
cout << "Funtest2:" << endl;
Funtest2();
getchar();
return 0;
}
運行結果