2012-08-22 32 views
3

提供類常量方法指針的類型是什麼?

class C { 
public: 
    int f (const int& n) const { return 2*n; } 
    int g (const int& n) const { return 3*n; } 
}; 

我們可以定義一個函數指針pC::f這樣。

typedef int (C::*Cfp_t) (const int&) const; 
Cfp_t p (&C::f); 

爲了確保p不改變(由p = &C::g;例如),我們可以這樣做::

const Cfp_t p (&C::f); 

int (C::*p) (const int&) const (&C::f); 

p定義可以使用typedef被分割

現在,這種情況下p的類型是什麼?我們如何在不使用typedef的情況下完成p的最後定義? 我知道,因爲它產生

int (__thiscall C::*)(int const &)const 

回答

7

變量類型p的是int (C::*const) (const int&) const,可以不用一個typedef它定義爲typeid (p).name()分不清最常量:

int (C::*const p) (const int&) const = &C::f; 

你的拇指法則是:要使您定義的對象/類型爲const,請將const關鍵字放在對象/類型的名稱旁邊。所以你也可以這樣做:

typedef int (C::*const Cfp_t) (const int&) const; 
Cfp_t p(&C::f); 
p = &C::f; // error: assignment to const variable 
+0

謝謝你這個快速簡潔的答案。 – Krokeledocus

相關問題