普通函式指標定義
1 int (*pfi)()
問題提出:
假設有如下類
1 class Screen
2 {
3 public:
4 int height() { return _height; }
5 int width() { return _width; }
6 //.
7 }
2 {
3 public:
4 int height() { return _height; }
5 int width() { return _width; }
6 //.
7 }
現在這樣賦值
1 pfi = &Screen::height;
2 //非法賦值,型別違例
2 //非法賦值,型別違例
因為指向成員函式指標包含三個方面:1)參數列(個數、型別) 2)返回型別 3) 所屬類型別
而普通的指向函式指標只包含兩個方面
正確的指向成員函式指標定義:
1 int (Screen::*pmf)();
2 pmf = &Screen:height;
3
4
為避免複雜的指標型別,使用typedef2 pmf = &Screen:height;
3
4
1 typedef int (Screen *PTR_TYPE)();
2 PTR_TYPE pmf = &Screen::height;
2 PTR_TYPE pmf = &Screen::height;
注意classname::* 語法
指向類成員的指標的使用:
1 int (Screen::*pmf)() = &Screen::height;
2 Screen myScreen, *bufScreen;
3
4 //直接呼叫成員函式
5 if(myScreen.height() == bufScreen->height())
6 //
7
8 //通過成員函式指標的等價呼叫
9 if((myScreen.*pmf)() == (bufScreen->*pmf)())
10 //
2 Screen myScreen, *bufScreen;
3
4 //直接呼叫成員函式
5 if(myScreen.height() == bufScreen->height())
6 //
7
8 //通過成員函式指標的等價呼叫
9 if((myScreen.*pmf)() == (bufScreen->*pmf)())
10 //
同樣道理,指向資料成員指標:
1 int Screen::* ps_screen = &_height
總結:與普通指標比較,加上classname::*
static成員的指標:
我們知道,靜態類成員屬於該類的全域性物件和函式,它們的指標是普通指標(請記住static成員函式沒用this指標)
1 class classname
2 {
3 public:
4 static void rai(double incr);
5 static double interest() { };
6 //
7 private:
8 static double _interestRate;
9 string _owner;
10 }
11
12 //ok
13 double *pd = &classname::_interestRate;
14 //error
15 double classname::*pd = &classname::_interestRate;
16
17 //ok
18 double (*pfunc)() = &classname::interest;
2 {
3 public:
4 static void rai(double incr);
5 static double interest() { };
6 //
7 private:
8 static double _interestRate;
9 string _owner;
10 }
11
12 //ok
13 double *pd = &classname::_interestRate;
14 //error
15 double classname::*pd = &classname::_interestRate;
16
17 //ok
18 double (*pfunc)() = &classname::interest;