gpt4 book ai didi

c++ - 常量方法指针的类型是什么?

转载 作者:太空狗 更新时间:2023-10-29 20:15:43 26 4
gpt4 key购买 nike

给定一个类

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

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

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

最佳答案

变量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

关于c++ - 常量方法指针的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12070522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com