C++语法小记---运算符重载

运算符重载
  • 运算符重载的本质也是对已有功能的扩展

  • 运算符重载的本质就是函数重载,只是函数变成了 operator + 运算符

  • 当成员函数和全局函数对运算符进行重载时,优先调用成员函数

  • 运算符重载为成员函数时,可以少一个参数,调用时,以右参数为参数进行函数调用

  • 不可以重载的运算符: . :: sizeof ?:

  • 运算符重载不改变参数个数,优先级,结合性

 

例子

  • 成员函数重载
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Test
 6 {
 7 private:
 8     int a;
 9     
10 public:
11     Test() {a = 0;}
12     
13     Test(int a) {this->a = a;}
14     
15     void show()
16     {
17         cout << "a = " << a << endl;
18     }
19 
20     Test operator + (Test& t)
21     {
22         Test rtn(0);
23         rtn.a = this->a + t.a;
24         return rtn;
25     }    
26 };
27 
28 int main()
29 {
30     Test t, t1(1), t2(2);
31     t = t1.operator + (t2);  //等同于 t = t1 + t2;
32     t.show();
33     return 0;
34 }

 

  • 全局函数重载
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Test
 6 {
 7 private:
 8     int a;
 9     
10 public:
11     Test() {a = 0;}
12     
13     Test(int a) {this->a = a;}
14     
15     int getA() {return a;}
16     
17     void setA(int a) {this->a = a;}
18     
19     void show()
20     {
21         cout << "a = " << a << endl;
22     }    
23 };
24 
25 Test operator + (Test& t1, Test& t2)
26 {
27     Test rtn(0);
28     rtn.setA(t1.getA() + t2.getA());
29     return rtn;
30 }    
31 
32 int main()
33 {
34     Test t, t1(1), t2(2);
35     t = t1 + t2;
36     t.show();
37     return 0;
38 }

 

重载数组操作符
  • 重载数组操作符只能是成员函数

  • 重载数组操作符的参数只能是一个,但是类型可以改变

  • 标准库中的string类,可以按照数组的方式访问

1 class Test
2 {
3     int data[10];
4 public:
5     int& operator [] (int i)
6     {
7         return data[i];
8     }
9 }

 

转载于:https://www.cnblogs.com/chusiyong/p/11294634.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值