2012-08-22 43 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

相关问题