c++ - 为什么获取成员函数指针值需要在类内部进行类名限定?

标签 c++ methods function-pointers dereference pointer-to-member

当在该类的一个成员函数中返回一个指向该类的成员函数指针时,我仍然必须指定该类。我不能简单地接受地址。例如,this code works fine :

class Foo {
public:
    void func(int param) { cout << param << endl; }
    void (Foo::*getPointer())(int) { return &Foo::func; }
};

但是如果在 getPointer 中我尝试简单地做:return &func 我得到这个错误:

prog.cpp: In member function 'void (Foo::* Foo::getPointer())(int)':
prog.cpp:8:43: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say '&Foo::func' [-fpermissive]
void (Foo::*getPointer())(int) { return &func; }

为什么我必须在我所在的上下文中指定类?

最佳答案

指针和指向成员的指针是不同的类型,我们可以从草案 C++ 标准部分 3.9.2 [basic.compound] 部分看到,其中包括指针的复合类型以及 指向非静态类成员的指针和注释:

Static class members are objects or functions, and pointers to them are ordinary pointers to objects or functions

这个问题我认为在 this quote in an answer from Johannes 中有很好的描述来自 Annotated C++ Reference Manual(ARM) :

Note that the address-of operator must be explicitly used to get a pointer to member; there is no implicit conversion ... Had there been, we would have an ambiguity in the context of a member function ... For example,

void B::f() {
    int B::* p = &B::i;   // ok
    p = B::i;         // error: B::i is an int
    p = &i;           // error: '&i'means '&this->i'
                      // which is an 'int*'

    int *q = &i;      // ok
    q = B::i;         // error: 'B::i is an int
    q = &B::i;        // error: '&B::i' is an 'int B::*'
}

特别是这些行:

int B::* p = &B::i; // OK

和:

p = &i; // error: '&i'means '&this->i' which is an 'int*'

展示合格名称和非合格名称之间的区别。

关于c++ - 为什么获取成员函数指针值需要在类内部进行类名限定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32842429/

相关文章:

function - 在没有 if-else/switch-case 语句的情况下控制程序流

c++ - 错误: C1083: Cannot open include file: 'boost/asio.hpp' : No such file or directory

ruby - “respond_to ?' versus '定义了吗?”

c++ - 使用 std::function 对象指向 C++11 中较大容器中结构的单个组件的迭代器

JavaScript 循环推送到新数组

javascript - 如何使用变量访问 javascript 对象方法?

c - 在 C 中,函数是否可以返回指向自身的指针?

c++ - 有没有办法在 C++ 中不使用缓存

c++ - 如何在 Visual Studio 2017 中的类型后禁用 * 的自动间距?

c# - 在VBA中编译支持声明函数的dll