首页 > 编程语言 > 详细

c++运算符递减运算符--重载

时间:2021-02-18 00:00:17      阅读:27      评论:0      收藏:0      [点我收藏+]

C++递增运算符--重载
作用:实现自定义类型的--操作。
operator--(){}

 1 #include<iostream>
 2 using namespace std;
 3 class Myinterge
 4 {
 5 public:
 6     friend ostream& operator<<(ostream& cout, Myinterge& p1);//友元
 7     Myinterge() 
 8     {
 9         m_A = 0;
10     }
11     Myinterge(int a)
12     {
13 
14         m_A = a;
15     }
16 
17     //重载前置--
18     Myinterge & operator--()//--运算符重载返回operator--(){}
19                            //引用是保证始终在同一个内存地址中进行-1操作
20     {
21         m_A--;
22         return *this;//返回自身
23     }
24     //重载后置--
25     Myinterge operator--(int)//int代表占位参数,用于区分前置--和后置--重载
26     {
27         Myinterge tem = *this;//先记录当前值
28         m_A--;
29         return tem;//返回-1之前的值
30     }
31 
32 private:
33     int m_A;
34 };
35 
36 ostream & operator<<(ostream& cout, Myinterge& p1)//全局左移运算符重载operator<<(){}
37 {
38     cout << p1.m_A;
39     return cout;
40 }
41 
42 
43 
44 int main()
45 {
46 
47     Myinterge p1(10);
48     cout << --(--p1) << endl;
49     cout << p1 << endl;
50 }

 

总结:前置++返回引用,后置++返回值,

c++运算符递减运算符--重载

原文:https://www.cnblogs.com/putobit/p/14410070.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!