Complex.h
#pragma once
#include <iostream> using namespace std;
//表示一个复数
class Complex
{
private:
double x, y;
public:
Complex(); //默认构造函数
Complex(double x, double y); //构造函数重载
Complex operator+(Complex & cmx) const; //'+'号运算符重载
Complex operator-(Complex & cmx) const; //'-'号运算符重载
Complex operator*(Complex & cmx) const; //'*'号运算符重载
Complex operator/(Complex & cmx) const; //'/'号运算符重载
Complex operator~() const; //'~'号运算符重载
Complex operator*(double & n) const; //'*'号运算符重载
friend Complex operator*(double & n, Complex & cmx); //友元函数,可用于表示[4.0*Complex类型]
friend ostream & operator<<(ostream & os, Complex & cmx); //友元函数,可用于表示[cout << Complex类型]
~Complex();
};
Complex.cpp
#include "Complex.h" Complex::Complex()
{
} Complex::Complex(double x, double y)
{
this->x = x;
this->y = y;
} Complex Complex::operator+(Complex & cmx) const
{
return Complex(x + cmx.x, y + cmx.y);
} Complex Complex::operator-(Complex & cmx) const
{
return Complex(x - cmx.x, y - cmx.y);
} Complex Complex::operator*(Complex & cmx) const
{
return Complex(x*cmx.x, y*cmx.y);
} Complex Complex::operator/(Complex & cmx) const
{
return Complex(x / cmx.x, y / cmx.y);
} Complex Complex::operator~() const
{
return Complex(x, -y);
} Complex Complex::operator*(double & n) const
{
return Complex(x*n, y*n);
} Complex operator*(double & n, Complex & cmx)
{
return cmx*n;
} ostream & operator<<(ostream & os, Complex & cmx)
{
os << cmx.x << "," << cmx.y << endl;
return os;
} Complex::~Complex()
{
}