2011-06-07 158 views
7

我是新來的C++。我想知道對象指針和成員函數的指針。我寫了這以下代碼:C++成員函數指針問題

代碼:

#include <iostream> 
using namespace std; 
class golu 
{ 
    int i; 
public: 
    void man() 
    { 
     cout<<"\ntry to learn \n"; 
    } 
}; 
int main() 
{ 
    golu m, *n; 
    void golu:: *t =&golu::man(); //making pointer to member function 

    n=&m;//confused is it object pointer 
    n->*t(); 
} 

但是當我編譯它,它表明了我的兩個錯誤這是繼:

pcc.cpp: In function ‘int main()’: 
pcc.cpp:15: error: cannot declare pointer to ‘void’ member 
pcc.cpp:15: error: cannot call member function ‘void golu::man()’ without object 
pcc.cpp:18: error: ‘t’ cannot be used as a function. 

我的問題是以下幾點:

  1. 我在這段代碼中做錯了什麼?
  2. 如何製作對象指針?
  3. 如何使指針指向一個類的成員函數以及如何使用它們?

請給我解釋一下這些概念。

回答

8

兩個錯誤糾正在這裏:

int main() 
{ 
    golu m, *n; 
    void (golu::*t)() =&golu::man; 

    n=&m; 
    (n->*t)(); 
} 
  1. 你想有一個函數指針
  2. 運營商的優先級是不是你所期望的一個我不得不加括號。 n->*t();被解釋爲(n->*(t())),而您想要(n->*t)();
+0

將您簡要介紹一下先決?我不瞭解這方面的優先權概念。 – Golu 2011-06-07 08:53:36

+0

是否修改回答適合你? – AProgrammer 2011-06-07 08:56:48

+0

請告訴我先決。 – Golu 2011-06-07 09:15:48

2

'void golu :: * t = & golu :: man();'應改爲'void(golu :: * t)()= & golu :: man;'你正試圖使用​​指針函數而不是指向靜態函數的結果!

+0

@xeo糾正了。 – Ali1S232 2011-06-07 08:52:47

1

(1)函數指針未正確聲明。

(2)你應該聲明這樣的:

void (golu::*t)() = &golu::man; 

(3)成員函數指針應與class的對象使用。

4

一個成員函數指針具有以下形式:

R (C::*Name)(Args...) 

R是返回類型,C是類的類型和Args...是任何可能的參數的函數(或無)。

有了這些知識,你的指針應該是這樣的:

void (golu::*t)() = &golu::man; 

注成員函數後失蹤()。這將試圖調用你剛纔得到的成員函數指針,這是不可能的,沒有一個對象。
現在,變得更具有可讀性用一個簡單的typedef:

typedef void (golu::*golu_memfun)(); 
golu_memfun t = &golu::man; 

最後,你並不需要一個指向對象使用成員函數,但是你需要括號:

golu m; 
typedef void (golu::*golu_memfun)(); 
golu_memfun t = &golu::man; 
(m.*t)(); 

括號是重要的,因爲()操作(函數調用)具有比.*(和->*)運算符更高的優先級(也稱precedence)。