【问题标题】:What is the type of a constant method pointer?常量方法指针的类型是什么?
【发布时间】:2023-04-02 23:26:01
【问题描述】:

给定一个班级

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 () 无法区分最外层的 const,因为它产生了

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

【问题讨论】:

    标签: c++ member-function-pointers


    【解决方案1】:

    变量p的类型是int (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
    

    【讨论】:

    • 感谢您快速简洁的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 2023-04-07
    • 2017-06-12
    相关资源
    最近更新 更多