如何使一个成员函数returns成为一个指向成员函数的指针?
How to make a member function which returns a pointer to a member function?
你好我想在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
是 class A
的成员,它是指向同一个 class 的成员 class 的指针,所以我不能从外面使用它,那么如何在 getter?
中 return
尽管有一种方法可以写出此声明,但您会发现使用 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
};
你可以在ptr
之后移动GetPtrFunc
并声明它decltype(ptr)
:
private:
void (A::*ptr)() = &A::Foo;
public:
decltype(ptr) GetPtrFunc() { return ptr; };
或者(没有顺序约束)只声明它 auto
,cretig 转到 @Jarod42 和 @user975989:
auto GetPtrFunc() { return ptr; };
你好我想在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
是 class A
的成员,它是指向同一个 class 的成员 class 的指针,所以我不能从外面使用它,那么如何在 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
};
你可以在ptr
之后移动GetPtrFunc
并声明它decltype(ptr)
:
private:
void (A::*ptr)() = &A::Foo;
public:
decltype(ptr) GetPtrFunc() { return ptr; };
或者(没有顺序约束)只声明它 auto
,cretig 转到 @Jarod42 和 @user975989:
auto GetPtrFunc() { return ptr; };