关于类的运算符重载:
分为两种: 1)将运算符重载为类的友元函数
2)将运算符重在为类的成员函数
一:
1 //friend 函数类型 operator 运算符(形参表){} 2 //通过重载 ,进行复数运算 3 #include <iostream> 4 using namespace std; 5 6 class Complex 7 { 8 private: 9 double real; 10 double image; 11 public: 12 Complex(double real=0.0,double image=0.0) 13 { 14 this->real=real; 15 this->image=image; 16 } 17 void display() 18 { 19 cout<<"("<<real<<","<<image<<")"<<endl; 20 } 21 friend Complex operator + (Complex A, Complex B) 22 { 23 return Complex (A.real+B.real,A.image+B.image); 24 } 25 friend Complex operator - (Complex A, Complex B); 26 friend Complex operator - (Complex A); // 重载取负为友元函数 27 friend Complex operator ++ (Complex &A); // 重载前置++为友元函数 28 friend Complex operator ++ (Complex &A, int); // 重载后置++为友元函数 29 }; 30 31 Complex operator -(Complex A,Complex B) 32 { 33 return Complex(A.real-B.real,A.image-B.image); 34 } 35 36 Complex operator -(Complex A) 37 { 38 return Complex(-A.real,-A.image); 39 } 40 41 Complex operator ++(Complex &A) 42 { 43 return Complex(++A.real,A.image); 44 } 45 46 Complex operator ++(Complex &A,int) 47 { 48 return Complex(A.real++,A.image); 49 } 50 51 int main() 52 { 53 Complex A(100.0,200.0),B(-10.0,20.0),C; 54 cout<<"A=", A.display(); 55 cout<<"B=", B.display(); 56 C=A+B; 57 cout<<"C=A+B=", C.display(); 58 C=A-B; 59 cout<<"C=A-B=", C.display(); 60 C=-A+B; 61 cout<<"C=-A+B", C.display(); 62 C=A++; 63 cout<<"C=A++, C=", C.display(); 64 C=++A; 65 cout<<"C=++A, C=", C.display(); 66 C=A+5; 67 C.display(); 68 return 0; 69 }
二:
1 //重载为类的成员函数 2 // 返回类型 类名::operator 运算符(形参表) 3 #include <iostream> 4 using namespace std; 5 class Complex 6 { 7 private: 8 double real; 9 double image; 10 public: 11 Complex(double real=0.0,double image=0.0) 12 { 13 this->real=real; 14 this->image=image; 15 } 16 void display() 17 { 18 cout<<"("<<real<<","<<image<<")"<<endl; 19 } 20 Complex operator + (Complex B); 21 Complex operator - (Complex B); 22 Complex operator - (); //取负重载成员函数 23 Complex operator ++ (); //前置++重载成员函数 24 Complex operator ++ (int); //后置--重载成员函数 25 26 }; 27 Complex Complex::operator + (Complex B) 28 { 29 return Complex(real+B.real,image+B.image); 30 } 31 32 Complex Complex::operator - (Complex B) 33 { 34 return Complex(real+B.real,image+B.image); 35 } 36 37 Complex Complex::operator - () 38 { 39 return Complex(-real,-image); 40 } 41 42 Complex Complex::operator ++() 43 { 44 return Complex(++real,image); 45 } 46 47 Complex Complex::operator ++(int) 48 { 49 return Complex(real++,image); 50 } 51 52 int main() 53 { 54 Complex A(100.0,200.0),B(-10.0,20.0),C; 55 cout<<"A=", A.display(); 56 cout<<"B=", B.display(); 57 C=A+B; 58 cout<<"C=A+B=", C.display(); 59 C=A-B; 60 cout<<"C=A-B=", C.display(); 61 C=-A+B; 62 cout<<"C=-A+B", C.display(); 63 C=A++; 64 cout<<"C=A++, C=", C.display(); 65 C=++A; 66 cout<<"C=++A, C=", C.display(); 67 C=A+5; 68 C.display(); 69 return 0; 70 }