鱼C论坛

 找回密码
 立即注册
查看: 1960|回复: 0

[技术交流] 运算符重载

[复制链接]
发表于 2016-5-12 09:53:36 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 红莲教主 于 2016-5-12 09:57 编辑
  1. #include <iostream>

  2. //using namespace std ;

  3. using std::cout;
  4. using std::endl;
  5. using std::ostream;

  6. class Complex
  7. {
  8. public:
  9.     Complex(int a , int b);
  10.     ~Complex();
  11.     Complex operator+(Complex com);
  12. private:
  13.     int a ;
  14.     int b ;

  15. friend ostream& operator<<(ostream& out ,Complex com );
  16. friend Complex operator-(Complex c1 ,Complex c2);
  17. };

  18. ostream& operator<<(ostream& out ,Complex com );
  19. Complex operator-(Complex c1 ,Complex c2);

  20. // 构造函数
  21. Complex::Complex(int a , int b)
  22. {
  23.     this->a = a ;
  24.     this->b = b ;
  25. }

  26. //析构函数
  27. Complex::~Complex()
  28. {

  29. }

  30. //重载加号运算符
  31. Complex Complex::operator+(Complex com)
  32. {
  33.     return Complex(a+com.a , b+com.b);
  34. }
  35. //重载减号预算福
  36. Complex operator-(Complex c1 ,Complex c2)
  37. {
  38.     return Complex(c1.a-c2.a , c1.b-c2.b);
  39. }
  40. //重载<<运算符
  41. ostream& operator<<(ostream& out ,Complex com )
  42. {
  43.     cout<<"("<<com.a<<","<<com.b<<")"<<endl;
  44.     return out ;
  45. }
  46. int main()
  47. {
  48.     Complex A(100,200);
  49.     Complex B(500,600);

  50.     cout<<(A+B);

  51.     Complex* C = new Complex(800,600);
  52.     Complex* D = new Complex(400,200);

  53.     cout<<(*C-*D);

  54.     delete C ;
  55.     delete D ;

  56.     return 0;
  57. }
复制代码
无标题.png
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 11:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表