2012-11-30 132 views
0

我想用一個指向C++成員函數,但它不工作:C++指向成員函數

指針聲明:

int (MY_NAMESPACE::Number::*parse_function)(string, int); 

指針分配:

parse_function = &MY_NAMESPACE::Number::parse_number; 

此調用完美(itd是地圖元素的迭代器):

printf("%s\t%p\n",itd->first.c_str(),itd->second.parse_function); 

但是這一次不工作:

int ret = (itd->second.*parse_function)(str, pts); 
$ error: 'parse_function' was not declared in this scope 

而這一次既不

int ret = (itd->second.*(MY_NAMESPACE::Number::parse_function))(str, pts); 
$ [location of declaration]: error: invalid use of non-static data member 'MY_NAMESPACE::Number::parse_function' 
$ [location of the call]: error: from this location 

我不understant爲什麼...

Thx提前!

+2

可能會更好,以熟悉的std ::功能 – goji

+0

請出示parse_number'的'聲明的容器,並itd'所屬的'。 – Angew

+0

第一次調用(在printf中)返回相關的東西(有一個開關情況,其中parsing_function受到「parse_function」影響,並且。與case1匹配的地圖的所有元素的打印結果爲0x2ad9d65302e0,所有與case2匹配的元素的打印結果是0x2ad9d65303b0。 – Jav

回答

1
int (MY_NAMESPACE::Number::*parse_function)(string, int); 

這表明,parse_function是指向一個構件功能類Number

This call works perfectly (itd is an iterator to elements of a map):

printf("%s\t%p\n",itd->first.c_str(),itd->second.parse_function);

以及由此我們可以看出parse_functionitd->second一員,不管這是。

該呼叫

int ret = (itd->second.*parse_function)(str, pts); 

或此調用

int ret = (itd->second.*(MY_NAMESPACE::Number::parse_function))(str, pts); 

成功,itd->second必須Number類型,它可能不是。並且parse_function必須被定義爲當前或封閉作用域(第一種情況)中的變量或類(第二種情況)的靜態變量。

所以,你需要一些Number和應用parse_function

Number num; 
(num.*(itd->second.parse_function))(str, pts); 

或用指針

Number *pnum; 
(pnum->*(itd->second.parse_function))(str, pts); 

更新

由於itd->second是一個號碼,你必須申請parse_function ,這是一個成員它,這樣

int ret = (itd->second.*(itd->second.parse_function))(str, pts); 
+0

'itd-> second'必須是'Number'類型......但它是! 'map :: iterator itd = mapNumbers.begin();'唉......我不明白 – Jav

+0

@Jav請看我更新的答案。 –

+0

@Jav請在您的問題中包含此*重要*信息。 –

0

您可以定義函數指針像這樣:type(*variable)() = &function; 例如:

int(*func_ptr)(); 
func_ptr = &myFunction; 

我可能只是沒有意識到你的代碼這個清晨,但問題可能是parse_function是一個指針,但你稱它爲itd->second.*parse_function。 指針與->*一起調用,因此請嘗試執行itd->second->parse_function

可能沒有修復任何東西,我真的不能看到你的代碼。 發佈更多信息,很難從兩行代碼中分辨出來。


下面是它如何在實際代碼使用的一個示例中,這一個呼叫func()通過cb()使用指針和參數只是:

int func() 
{ 
    cout << "Hello" << endl; 
    return 0; 
} 

void cb(int(*f)()) 
{ 
    f(); 
} 

int main() 
{ 
    int(*f)() = &func; 
    cb(f); 
    return 0; 
} 
+0

您在'int(* f)'後面錯過了分號)=&func'(對不起,挑剔):) – peterph

+0

好抓,固定。 – 2012-11-30 09:23:59

+0

指向函數的指針與C++中指向成員函數的指針有很大不同。仔細閱讀問題 – SomeWittyUsername