菜鸟的博客

纵有疾风起,人生不言弃。

导航

2023.4.21 (2)

 1 //递增运算符的重载
 2 #include <iostream>
 3 using namespace std;
 4 class Myinteger
 5 {
 6     friend ostream& operator<<(ostream &cout,Myinteger &myint);
 7 public:
 8 
 9     Myinteger()
10     {
11         m_Num = 0;
12     }
13     //重载前置++运算符
14     Myinteger& operator++()//返回引用为了对一个数值进行操作
15     {
16         m_Num++;
17         return *this;//返回自身
18     }
19     //重载后置++运算符
20     Myinteger operator++(int)//int代表占位参数,可以区分前置后置递增
21     {
22         //先记录当时的结果
23         Myinteger temp = *this;
24         //后递增
25         m_Num++;
26         //返回记录的结果
27         return temp;
28     }
29 private:
30     int m_Num;
31 };
32 //重载<<运算符
33 ostream& operator<<(ostream &cout,Myinteger &myint)
34 {
35     cout<<myint.m_Num<<endl;
36     return cout;
37 }
38 void test01()
39 {
40     Myinteger myint;
41     cout<<++(++myint)<<endl;
42     cout<<myint<<endl;
43 }
44 void test02()
45 {
46     Myinteger myint;
47     cout<<myint++<<endl;
48     cout<<myint<<endl;
49 }
50 int main()
51 {
52     test01();
53     test02();
54     return 0;
55 }

 

posted on 2023-04-21 22:00  hhmzd233  阅读(11)  评论(0编辑  收藏  举报