C++Note 运算符重载 递增 operator++

递增运算符重载

作用:通过重载递增运算符,实现自己的整型数据

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 //递增运算符重载
 4 //自定义整型
 5 class MyInteger
 6 {
 7     friend ostream& operator<<(ostream& cout, MyInteger mi);
 8     //友元 全局函数可以访问类内私有变量
 9 public:
10     MyInteger()
11     {
12         m_Num = 0;
13     }
14     //重载  前置++ 运算符
15     MyInteger& operator++()//返回引用是为了对同一地址的单一数据进行操作
16     {
17         m_Num++;
18         return *this;//对当前m_Num自增后  解引用的值进行 返回  且返回类型是 MyInteger
19     }
20     //重载  后置++ 运算符
21     //前置递增返回引用  后置递增返回为值 因为temp会被自动释放 
22     MyInteger operator++(int)//int代表占位参数 用于区分前置和后置函数重载
23     {
24         //先记录当时结果 后递增 最后将记录结果返回
25         MyInteger temp = *this;
26         m_Num++;
27         return temp;
28     }
29 private:
30     int m_Num;
31 };
32 //重载左运算符
33 ostream& operator<<(ostream& cout, MyInteger mi)
34 {
35     cout << mi.m_Num;
36     return cout;
37 }
38 void test()//前置递增测试
39 {
40     MyInteger mi;
41     cout << ++mi << endl;
42     cout << ++mi << endl;
43 }
44 void test1()//后置递增测试
45 {
46     MyInteger mi;
47     cout << mi++ << endl;
48     cout << mi++ << endl;
49 }
50 int main()
51 {
52     //test();
53     test1();
54     system("pause");
55     return 0;
56 }
复制代码

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

posted on   廿陆  阅读(10)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示