#include<iostream>
using namespace std;
class Complex
{
public:
friend ostream& operator<<(ostream& _cout, Complex c); //輸出函數需要訪問私有成員,聲明爲友元函數
Complex(double real = 0.0, double image = 0.0);
Complex(const Complex& c);
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);
Complex& operator+=(const Complex& c);
Complex& operator-=(const Complex& c);
Complex& operator*=(const Complex& c);
Complex& operator/=(const Complex& c);
~Complex();
private:
double _real;
double _image;
};
Complex::Complex(double real, double image):// 構造函數
_real(real),
_image(image)
{
}
Complex::Complex(const Complex& c) :// 拷貝構造
_real(c._real)
, _image(c._image)
{
}
Complex& Complex::operator=(const Complex &c) // 賦值運算符重載 返回值爲引用
{
if (this != &c)
{
this->_real = c._real;
this->_image = c._image;
}
return *this;
}
Complex Complex::operator+(const Complex &c)// 複數相加 +運算符重載
{
Complex temp;
temp._real = this->_real + c._real;
temp._image = this->_image + c._image;
return temp;
}
Complex Complex::operator-(const Complex &c)// 複數相減 -運算符重載
{
Complex temp;
temp._real = this->_real - c._real;
temp._image = this->_image - c._image;
return temp;
}
Complex Complex::operator*(const Complex &c)// 複數相乘 *運算符重載
{
Complex temp;
temp._real = this->_real*c._real - this->_image*c._image;
temp._image = this->_real*c._image + c._real*this->_image;
return temp;
}
Complex Complex::operator/(const Complex &c)// 複數相除 /運算符重載
{
Complex temp;
temp._real = (this->_real * c._real + this->_image*c._image) / (c._real*c._real + c._image *c._image);
temp._image = (c._real * this->_image - this->_real*c._image) / (c._real*c._real + c._image *c._image);
return temp;
}
Complex& Complex:: operator+=(const Complex &c)// 複數+=運算符重載
{
this->_real = this->_real + c._real;
this->_image = this->_image + c._image;
return *this;
}
Complex& Complex:: operator-=(const Complex &c)//// 複數-=運算符重載
{
this->_real = this->_real - c._real;
this->_image = this->_image - c._image;
return *this;
}
Complex& Complex::operator*=(const Complex& c)// 複數 *=運算符重載
{
this->_real = this->_real*c._real - this->_image*c._image;
this->_image = this->_real*c._image + c._real*this->_image;
return *this;
}
Complex& Complex::operator/=(const Complex& c)// 複數 /=運算符重載
{
this->_real = (this->_real * c._real + this->_image*c._image) / (c._real*c._real + c._image *c._image);
this->_image = (c._real * this->_image - this->_real*c._image) / (c._real*c._real + c._image *c._image);
return *this;
}
Complex::~Complex()// 析構函數
{
}
ostream& operator<<(ostream& _cout, Complex c)// 輸出運算符<<重載
{
_cout << c._real << " " << c._image;
return _cout;
}
int main()
{
Complex a(2, 0);
Complex b(a);
a *= b;
cout << a << endl;
system("pause");
return 0;
}