Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7678894
  • 博文数量: 961
  • 博客积分: 15795
  • 博客等级: 上将
  • 技术积分: 16612
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-07 14:23
文章分类

全部博文(961)

文章存档

2016年(1)

2015年(61)

2014年(41)

2013年(51)

2012年(235)

2011年(391)

2010年(181)

分类: C/C++

2011-03-30 16:52:52

  1. /****************************************************
  2. * 文件名:
  3. * 功能:运算符重载简单应用
  4. * 说明:运算符重载实际上就是函数重载        
  5. * 时间:2011-3-30          --Lzy
  6. ****************************************************/
  7. //成员函数重载运算符

  8. #include <iostream.h>

  9. class complex
  10. {
  11. private:
  12.     double x, y;

  13. public:
  14.     complex(double xx = 0, double yy = 0){x = xx; y = yy;}

  15.     double getx(){return x;}
  16.     double gety(){return y;}

  17.     void display()
  18.     {
  19.         cout<<"("<<x;
  20.         if(y>0)
  21.             cout<<"+"<<y<<"*i)";
  22.         else if(y<0)
  23.             cout<<y<<"*i)";
  24.         else
  25.             cout<<")"<<endl;
  26.     }
  27.     complex operator + (complex &c1);
  28. };

  29. complex complex::operator + (complex &c1)    //定义重载算术运算符

  30. {
  31.     complex c;
  32.     c.x = this->x + c1.x;
  33.     c.y = this->y + c1.y;
  34.     return c;
  35. }

  36. void main()
  37. {
  38.     complex c1(3,4),c2(4,-5),c3;
  39.     c3= c1+c2;

  40.     c1.display();
  41.     cout<<"+";
  42.     c2.display();
  43.     cout<<"=";
  44.     c3.display();
  45.     cout<<endl;
  46. }


  47. //友元函数重载

  48. #include <iostream.h>

  49. class complex
  50. {
  51. private:
  52.     double x, y;
  53.     
  54. public:
  55.     complex(double xx = 0, double yy = 0){x = xx; y = yy;}

  56.     double getx(){return x;}
  57.     double gety(){return y;}

  58.     void display()
  59.     {
  60.         cout<<"("<<x;
  61.         if(y>0)
  62.             cout<<"+"<<y<<"*i)";
  63.         else if(y<0)
  64.             cout<<y<<"*i)";
  65.         else
  66.             cout<<")"<<endl;
  67.     }
  68.     friend complex operator * (complex &c1,complex &c2);
  69. };

  70. complex operator * (complex &c1, complex &c2)    //定义重载算术运算符

  71. {
  72.     complex c;
  73.     c.x = c2.x * c1.x;
  74.     c.y = c2.y * c1.y;
  75.     return c;
  76. }

  77. void main()
  78. {
  79.     complex c1(3,4),c2(4,-5),c3;
  80.     c3= c1*c2;

  81.     c1.display();
  82.     cout<<"*";
  83.     c2.display();
  84.     cout<<"=";
  85.     c3.display();
  86.     cout<<endl;
  87. }
阅读(2168) | 评论(0) | 转发(2) |
0

上一篇:虚基类简单应用

下一篇:虚函数简单应用

给主人留下些什么吧!~~