码迷,mamicode.com
首页 > 其他好文 > 详细

运算符重载

时间:2016-02-06 14:21:00      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Complex
 6 {
 7 private:
 8     int a, b;
 9 public:
10     Complex(int a, int b) :a(a), b(b)
11     {}
12 
13 //      Complex& operator+(Complex &c)          //放在类里
14 //      {
15 //          this->a = this->a + c.a;
16 //          this->b = this->b + c.b;
17 //          return *this;
18 //      }
19 
20     friend Complex& operator+(Complex &c1, Complex &c2);
21 };
22 
23 Complex& operator+(Complex &c1, Complex &c2)    //放在类外,如果a, b不是类Complex的私有变量的话,是可以不用friend函数来声明重载函数的, 这就是以前在cocos2d-x里学到的全局重载函数
24 {
25     Complex c3(1, 1);
26     c3.a = c1.a + c2.a;
27     c3.b = c1.b + c2.b;
28     return c3;
29 }
30 
31 int main()
32 {
33     Complex c1(1, 2), c2(3, 4);
34     Complex c3 = c1 + c2;
35 
36     system("pause");
37     return 0;
38 }

 两种方式重载

二元运算符

全局(友元)   必须有两个参数,分别代表左右操作数

成员   只能有一个参数代表右操作数,左操作数由this指针隐藏代替,

运算符重载

标签:

原文地址:http://www.cnblogs.com/c-slmax/p/5184013.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!