常量方法指针的类型是什么

What is the type of a constant method pointer?

本文关键字:类型 是什么 指针 方法 常量      更新时间:2023-10-16

给定一个类

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

我们可以像这样定义函数指针pC::f

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

p的定义可以使用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的类型是什么?我们如何在不使用typedef的情况下完成p的最后一个定义?我知道typeid (p).name ()无法区分最外层的常量,因为它会产生

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

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

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

您的经验法则是:要使您定义的对象/类型为常量,请将const关键字放在对象/类型的名称旁边。所以你也可以做:

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