3

给定一个班级

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

p我们可以像这样定义一个函数指针C::f

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

的定义p可以使用 a 进行拆分typedef

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

为了确保p不会改变(p = &C::g;例如),我们可以这样做:

const Cfp_t p (&C::f);

现在,p这种情况下的类型是什么?我们如何在p不使用 typedef 的情况下完成最后一个定义?我知道typeid (p).name ()无法区分最外面的 const 因为它产生

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

1 回答 1

7

变量的类型pint (C::*const) (const int&) const,您可以在没有 typedef 的情况下将其定义为:

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
于 2012-08-22T09:55:39.263 回答