有关指针 -> 和* 的重载

 1, #include<iostream>
 2   2 #include<string>
 3   3 using namespace std;
 4   4 class test{
 5   5         int i;
 6   6 public:
 7   7         test(int i){
 8   8                 cout << "test(int i)" << i << endl;
 9   9                 this->i = i;
10  10         }
11  11         int get(){
12  12                 return i;
13  13         }
14  14         ~test(){}
15  15 };
16  16 class pointer{
17  17         test* mp;
18  18 public:
19  19         pointer(test*p = NULL){
20  20                 mp = p;//成员变量赋值
21  21         }
22  22         test* operator->(){
23  23                 return mp;
24  24         }
25  25         test& operator*(){
26  26                 return *mp;
27  27         }
28 28         ~pointer(){
29  29                 cout << "~pointer()" << endl;
30  30                 delete mp;
31  31         }
32  32 };
33  33 int main(){
34  34         for(int i=0;i<5;i++){
35  35                 pointer p = new test(i);
36  36                 cout << p->get() << endl;
37  37         }
38  38         return 0;
39  39 }
40 //结果
41 test(int i)0
42 0
43 ~pointer()
44 test(int i)1
45 1
46 ~pointer()
47 test(int i)2
48 2
49 ~pointer()
50 test(int i)3
51 3
52 ~pointer()
53 test(int i)4
54 4
55 ~pointer()

 

posted @ 2019-11-17 22:35  刘大侠GG_B  阅读(227)  评论(0编辑  收藏  举报