友元函数编写运算符重载

  1. /* 
  2. *Copyright (c) 2016,烟台大学计算机学院 
  3. *All rights reserved. 
  4. *文件名称:test.cpp 
  5. *作    者:陈传祯 
  6. *完成日期:2016年6月14日 
  7. *版 本 号:1.0 
  8. * 
  9. *问题描述:简单的运算符重载 
  10. *输入描述: 两个复数, 
  11. *程序输出: 两个复数相加减的结果 
  12. */  
  13. #include <iostream>   
  14. using namespace std;  
  15. class Complex  
  16. {  
  17. public:  
  18.       Complex(){real=0;imag=0;}  
  19.       Complex(double r,double i){real=r;imag=i;}  
  20.       friend Complex operator+(Complex&c1, Complex &c2);  
  21.      friend Complex operator-(Complex&c1 ,Complex &c2);  
  22.       void display();  
  23. private:  
  24.       double real;  
  25.       double imag;  
  26. };  
  27. Complex operator+(Complex&c1,Complex &c2)  
  28. {  
  29.       Complex c;  
  30.       c.real=c1.real+c2.real;  
  31.       c.imag=c1.imag+c2.imag;  
  32.       return c;  
  33. }  
  34. Complex operator-(Complex&c1, Complex &c2)  
  35. {  
  36.       Complex c;  
  37.       c.real=c1.real-c2.real;  
  38.       c.imag=c1.imag-c2.imag;  
  39.       return c;  
  40. }  
  41.   
  42. void Complex::display()  
  43. {  
  44.       cout<<real<<","<<imag<<"i"<<endl;  
  45. }  
  46.   
  47. int main()  
  48. {  
  49.     Complex c1(3,4),c2(5,-10),c3;  
  50.     cout<<"c1=";  
  51.     c1.display();  
  52.     cout<<"c2=";  
  53.     c2.display();  
  54.     cout<<"c1+c2=";  
  55.     c3=c1+c2;  
  56.     c3.display();  
  57.     cout<<"c1-c2=";  
  58.     c3=c1-c2;  
  59.     c3.display();  
  60.     return 0;  
  61. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值