将指针分配给成员函数

时间:2020-07-22 19:54:33

标签: c++

我正在跟踪earlier question,但是我的问题与类型问题有关。

如何将指向成员函数C::f()的指针分配给m指针?

成员函数是否必须是静态的?

#include <iostream>
using namespace std;

struct nullpt_t {
    template<class T>
    inline operator T*() const { return 0; }
    
    template<class C, class T>
    inline operator T C::*() const { return 0; }
};
nullpt_t nullpt;
    
struct C {
    void f() {cout << "here" << endl;}
};
    
int main(void)
{
    int *ptr = nullpt;       
    void (C::*m)() = nullpt;
    // now assign m with member function f()?
}

1 个答案:

答案 0 :(得分:1)

您要做的就是获取一个指向成员函数的指针并为其分配:

m = &C::f;

这仅适用于非静态函数。静态函数没有与之关联的实例,因此您可以使用指向它们的标准函数指针。 (指向成员的指针是特殊的,因为您必须提供一个实例来解除对指针的引用。请注意,正常调用静态成员函数时不必这样做。)

struct C {
    void f() {cout << "here" << endl;}
    static void g() {cout << "here static" << endl;}
};

int main() {
    // Pointer-to-member-function (non-static)
    void (C::*m)() = &C::f;
    // Standard function pointer (static)
    void (*n)() = &C::g;
}