increment/decrement/dereference

 

复制代码
 1 #include <vector>
 2 #include <deque>
 3 #include <algorithm>
 4 #include <iostream>
 5 #include <ostream>
 6 #include <iterator>
 7 using namespace std;
 8 
 9 class INT
10 {
11     friend ostream& operator<<(ostream &os, const INT& i);
12 public:
13     INT(int i) : m_i(i){}
14     //prefix:increment and then fetch
15     INT& operator ++()
16     {
17         ++(this->m_i);//随着class的不同,该行应该有不同的操作
18         return *this;
19     }
20 
21     //postfix:fetch and then increment
22     const INT operator ++(int)
23     {
24         INT temp = *this;
25         ++(*this);
26         return temp;
27     }
28 
29     //prefix:decrement and then fetch
30     INT& operator --()
31     {
32         --(this->m_i);
33         return *this;
34     }
35 
36     //postfix:fetch and then decrement
37     const INT operator --(int)
38     {
39         INT temp = *this;
40         --(*this);
41         return temp;
42     }
43 
44     //dereference
45     int& operator*() const
46     {
47         return (int&)m_i;
48     }
49 
50 private:
51     int m_i;
52 };
53 
54 ostream& operator<<(ostream& os, const INT& i)
55 {
56     os << '[' << i.m_i << ']';
57     return os;
58 }
59 
60 int main( )
61 {
62     INT i(5);
63     cout << i++ << endl;
64     cout << ++i << endl;
65     cout << i-- << endl;
66     cout << --i << endl;
67     cout << *i << endl;
68     return 0;
69 }
复制代码

Output:

[5]
[7]
[7]
[5]
5
posted @   PKICA  阅读(288)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示