C++:友元运算符重载函数

运算符重载函数:实现对象之间进行算数运算,(实际上是对象的属性之间做运算),包括+(加号)、-(减号)、*、/、=、++、--、-(负号)、+(正号)

运算符重载函数分为:普通友元运算符重载函数、成员友元运算符重载函数、成员运算符重载函数

运算符运算符重载函数按运算类型为:双目运算符重载函数,如加、减、乘、除、赋值;   单目运算符重载函数:自加、自减、取正负号

切记:成员运算符. 和->,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();
//friend为友元函数的关键字,这两个符号运算符重载函数的参数类型至少有一个类类型或者类的引用
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

 

posted @ 2015-08-26 16:11  XYQ全哥  阅读(6946)  评论(0编辑  收藏  举报