c++ - 为什么这种模式不能在成员函数中使用?

标签 c++

我在全局函数中使用了成员函数指针:

class ClassA
{
public:
    void FuncA(void);
    ...
}
void GlobalFunc(void)
{
    typedef void(ClassA::*MemberFnPtr)(void);
    MemberFnPtr fnPtrA = &ClassA::FuncA;
    ...
}

而且这样的模式也很完美(因为 operator::的优先级高于 operator&)

typedef void(ClassA::*MemberFnPtr)(void);
MemberFnPtr fnPtrA = &(ClassA::FuncA);
...

但是,当我在成员函数中使用后一种模式时,出现了一些奇怪的东西 error C2276:"&";

我读过一些关于 std::bindstd::function 的内容,我认为这对我来说会更好。但是,我真的很想知道当我在成员函数中使用后一种模式时发生了什么,有人可以帮忙吗?

最佳答案

您不应该在成员函数的名称周围使用括号:

MemberFnPtr fnPtrA = &(ClassA::FuncA); // not good
MemberFnPtr fnPtrA = &ClassA::FuncA; // good

C++ 标准在第 5.3.1 节中明确提到了这一点:

Note: that is, the expression &(qualified-id), where the qualified-id is enclosed in parentheses, does not form an expression of type “pointer to member.”

关于c++ - 为什么这种模式不能在成员函数中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33344355/

相关文章:

c++ - cout this_thread::sleep_for?

c++ - 如何使用 OpenCV 在 C++ 中访问 3D 直方图值?

c# - 从 C++ 到 C# 的 DirectX 结构数组的困难编码

c++ - 单例中的全局对象

c++ - 包含未使用的 header 是否会影响 cpp 编译时间?

c++ - 如果构造函数被显式默认或删除,为什么自 C++20 以来聚合初始化不再起作用?

c++ - new 必须用于创建结构?

c++ - OpenCV 垫不能在 Debug模式下工作

c++ - 为什么 C 允许我调用未声明的函数?

c++ - 怎么可能知道是什么导致了异常