关键词搜索

源码搜索 ×
×

语法糖---C++的运算符重载

发布2014-11-08浏览8117次

详情内容

         语法糖(Syntactic sugar),也译为糖衣语法,是由英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。

       下面, 我们来看看C++中运算符的重载:

 

  1. #include <iostream>
  2. using namespace std;
  3. // 复数类
  4. class C
  5. {
  6. private:
  7. int x;
  8. int y;
  9. public:
  10. C()
  11. {
  12. x = 0;
  13. y = 0;
  14. }
  15. C(int xx, int yy)
  16. {
  17. x = xx;
  18. y = yy;
  19. }
  20. // 只考虑x 和 y都是非负整数
  21. void print()
  22. {
  23. if(0 == x && 0 == y)
  24. {
  25. cout << 0 << endl;
  26. }
  27. else if(0 == y)
  28. {
  29. cout << x << endl;
  30. }
  31. else if(0 == x)
  32. {
  33. cout << "j" << y << endl;
  34. }
  35. else
  36. {
  37. cout << x <<" + j" << y << endl;
  38. }
  39. }
  40. // 利用成员函数重载复数的 +=
  41. void operator+=(const C& c)
  42. {
  43. x += c.x;
  44. y += c.y;
  45. }
  46. };
  47. int main()
  48. {
  49. C c1(1, 1);
  50. c1.print();
  51. C c2(2, 2);
  52. c2.print();
  53. c2.operator += (c1); // operator += 其实就是函数名
  54. c2.print();
  55. c2 += c2; // 语法糖:运算符重载了, 好看了, 但功能一样
  56. c2.print();
  57. int i = 1;
  58. int j = 2;
  59. j += i;
  60. cout << j << endl;
  61. c1 + c2; // error, 未定义行为
  62. return 0;
  63. }

 

      语法糖, 好甜吐舌头

 

      我们知道, 成员函数可以直接访问私有的数据成员, 友元函数也能, 故上面程序可以改为:

 

  1. #include <iostream>
  2. using namespace std;
  3. // 复数类
  4. class C
  5. {
  6. private:
  7. int x;
  8. int y;
  9. public:
  10. C()
  11. {
  12. x = 0;
  13. y = 0;
  14. }
  15. C(int xx, int yy)
  16. {
  17. x = xx;
  18. y = yy;
  19. }
  20. // 只考虑x 和 y都是非负整数
  21. void print()
  22. {
  23. if(0 == x && 0 == y)
  24. {
  25. cout << 0 << endl;
  26. }
  27. else if(0 == y)
  28. {
  29. cout << x << endl;
  30. }
  31. else if(0 == x)
  32. {
  33. cout << "j" << y << endl;
  34. }
  35. else
  36. {
  37. cout << x <<" + j" << y << endl;
  38. }
  39. }
  40. friend void operator+=(C& c1, const C& c2);
  41. };
  42. // 利用友元函数重载复数的 +=
  43. void operator+=(C& c1, const C& c2)
  44. {
  45. c1.x += c2.x;
  46. c1.y += c2.y;
  47. }
  48. int main()
  49. {
  50. C c1(1, 1);
  51. c1.print();
  52. C c2(2, 2);
  53. c2.print();
  54. operator += (c1, c2); // operator += 其实就是函数名
  55. c1.print();
  56. c1 += c1; // 语法糖:运算符重载了, 好看了, 但功能一样
  57. c1.print();
  58. int i = 1;
  59. int j = 2;
  60. j += i;
  61. cout << j << endl;
  62. c1 + c2; // error, 未定义行为
  63. return 0;
  64. }

 

 

 

 

 

 

 

 

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载