标签:
运算符重载函数:实现对象之间进行算数运算,(实际上是对象的属性之间做运算),包括+(加号)、-(减号)、*、/、=、++、--、-(负号)、+(正号)
运算符重载函数分为:友元运算符重载函数、成员运算符重载函数
运算符运算符重载函数按运算类型为:双目运算符重载函数,如加、减、乘、除、赋值; 单目运算符重载函数:自加、自减、取正负号
切记:成员运算符. 和->,sezeof等不能重载。运算符重载函数的参数至少有一个是类类型或引用类型,
下面为友元运算符重载函数举例:
1 #include<iostream> 2 using namespace std; 3 class Complex 4 { 5 public: 6 Complex(double r=0.0,double i=0.0); 7 void print(); 8 friend Complex operator+(Complex &a,Complex &b); 9 friend Complex operator-(Complex &a,Complex &b); 10 private: 11 double real; 12 double imag; 13 }; 14 Complex::Complex(double r,double i) 15 { 16 real = r; 17 imag = i; 18 } 19 Complex operator+(Complex &a,Complex &b) 20 { 21 Complex temp; 22 temp.real = a.real + b.real; 23 temp.imag = a.imag + b.imag; 24 return temp; 25 } 26 Complex operator-(Complex &a,Complex &b) 27 { 28 Complex temp; 29 temp.real = a.real - b.real; 30 temp.imag = a.imag - b.imag; 31 return temp; 32 } 33 void Complex::print() 34 { 35 cout<<real; 36 if(imag>0) cout<<"+"; 37 if(imag!=0) cout<<imag<<‘i‘<<endl; 38 } 39 int main(int agrs,const char *agrv[]) 40 { 41 Complex A1(2.3,4.6),A2(3.6,2.8),A3,A4; 42 A3 = A1 + A2;//A3 = operator+(A1,A2); 43 A4 = A1 - A2;//A4 = operator-(A1-A2); 44 A1.print(); 45 A2.print(); 46 A3.print(); 47 A4.print(); 48 49 return 0; 50 }
运行结果:
2.3+4.6i
3.6+2.8i
5.9+7.4i
-1.3+1.8i
Program ended with exit code: 0
标签:
原文地址:http://www.cnblogs.com/XYQ-208910/p/4760757.html