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

 

转载于:https://www.cnblogs.com/XYQ-208910/p/4760757.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值