你好,我想在private scope
下声明一个指向成员函数的指针作为成员数据,并制作一个getter
从外部获取它:
class A
{
public:
A(){ ptr = Foo;} // for example: ok
void Foo(){ cout << "Foo()" << endl;}
void Bar(){ cout << "Bar()" << endl;};
void (A::*)() GetPtrFunc() {return ptr;} // error here?
private:
void (A::*ptr)(); // ok here
};
如您所见,ptr
是类 A
的成员,它是指向同一类的成员类的指针,所以我不能从外部使用它,所以如何用 getter 返回它?
最佳答案
虽然有一种方法可以写出这个声明,但您会发现使用 typedef
会更容易混淆:
typedef void (A::*mem_func_ptr)();
mem_func_ptr GetPtrFunc() {return ptr;}
private:
mem_func_ptr ptr; // ok here
此外,您在构造函数中的初始化不正确。完整的更正示例:
#include <iostream>
using namespace std;
class A
{
public:
A(){ ptr = &A::Foo;}
void Foo(){ cout << "Foo()" << endl;}
void Bar(){ cout << "Bar()" << endl;};
typedef void (A::*mem_func_ptr)();
mem_func_ptr GetPtrFunc() {return ptr;} // error here?
private:
mem_func_ptr ptr; // ok here
};
关于c++ - 如何创建一个返回成员函数指针的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41903463/