本文連接:https://www.cnblogs.com/jqdy/p/14351991.html
有很多例子介紹C編程時使用結構(struct)模擬類(class)的方法。這些例子有個共同的特點,都沒有涉及到class中this指針的處理方法,造成類的“方法”處理“屬性”必須把需要的多個“屬性”以參數形式傳遞給“方法”,從而造成效率和空間的額外支出。
例如,下面這個例子中在使用方法add()時,必須把兩個屬性a、b直接以參數形式進行傳遞(第18行):
1 typedef struct{ 2 int a; 3 int b; 4 int(*add)(int, int); 5 }AccTypedef; 6 7 int Add(int a, int b) 8 { 9 return a + b; 10 } 11 12 void main() 13 { 14 int result; 15 //類初始化 16 AccTypedef myAcc = {1, 2, Add};
17 //使用add方法時
18 result = myAcc.add(myAcc.a, myAcc.b);
19 //......
20 }
那么,能不能借助this指針的概念簡化這個過程呢?
在Keil中如下處理即可:
1 typedef struct thisAcc{ 2 int a; 3 int b; 4 int (*add)(struct thisAcc*); 5 }AccTypedef; 6 7 int Add(AccTypedef* _this) 8 { 9 return _this->a + _this->b; 10 } 11
12 void main()
13 {
14 int result;
15 //類初始化
16 AccTypedef myAcc = {1, 2, Add};
17 //使用add方法時
18 result = myAcc.add(&myAcc);
19 //......
20 }
定義結構類型 AccTypedef 時采用 “typedef struct 結構名 { 結構體 } 類型名”的方式,其中“結構名”是不能省略的。
以第二個程序片段為例說明:
第1行中的“結構名” thisAcc 不能省略,它要提供給第4行定義 int (* add)(struct thisAcc*)時使用,指示編譯器 thisAcc 究竟為何方神聖,因為此時編譯器還沒有讀到第5行的 AccTypedef,不能使用 int (* add)(AccTypedef*)的方式。另外第四行中的 struct 也不能省略,否則編譯器不清楚 thisAcc 是一個結構了。
這樣處理后,在使用“方法”add時,僅將myAcc的地址傳入即可,見第18行。這個傳入的地址 &myAcc,即為 this 指針。
通過這種處理方法,就達到了this指針的效果。
