Complex.h
1 #pragma once 2 #include <iostream> 3 4 using namespace std; 5 //表示一个复数 6 class Complex 7 { 8 private: 9 double x, y; 10 public: 11 Complex(); //默认构造函数 12 Complex(double x, double y); //构造函数重载 13 Complex operator+(Complex & cmx) const; //‘+‘号运算符重载 14 Complex operator-(Complex & cmx) const; //‘-‘号运算符重载 15 Complex operator*(Complex & cmx) const; //‘*‘号运算符重载 16 Complex operator/(Complex & cmx) const; //‘/‘号运算符重载 17 Complex operator~() const; //‘~‘号运算符重载 18 Complex operator*(double & n) const; //‘*‘号运算符重载 19 friend Complex operator*(double & n, Complex & cmx); //友元函数,可用于表示[4.0*Complex类型] 20 friend ostream & operator<<(ostream & os, Complex & cmx); //友元函数,可用于表示[cout << Complex类型] 21 ~Complex(); 22 };
Complex.cpp
1 #include "Complex.h" 2 3 4 5 Complex::Complex() 6 { 7 } 8 9 Complex::Complex(double x, double y) 10 { 11 this->x = x; 12 this->y = y; 13 } 14 15 Complex Complex::operator+(Complex & cmx) const 16 { 17 return Complex(x + cmx.x, y + cmx.y); 18 } 19 20 Complex Complex::operator-(Complex & cmx) const 21 { 22 return Complex(x - cmx.x, y - cmx.y); 23 } 24 25 Complex Complex::operator*(Complex & cmx) const 26 { 27 return Complex(x*cmx.x, y*cmx.y); 28 } 29 30 Complex Complex::operator/(Complex & cmx) const 31 { 32 return Complex(x / cmx.x, y / cmx.y); 33 } 34 35 Complex Complex::operator~() const 36 { 37 return Complex(x, -y); 38 } 39 40 Complex Complex::operator*(double & n) const 41 { 42 return Complex(x*n, y*n); 43 } 44 45 Complex operator*(double & n, Complex & cmx) 46 { 47 return cmx*n; 48 } 49 50 ostream & operator<<(ostream & os, Complex & cmx) 51 { 52 os << cmx.x << "," << cmx.y << endl; 53 return os; 54 } 55 56 Complex::~Complex() 57 { 58 }
时间: 2024-10-03 22:40:02