C++运行符重载、友元函数
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 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。