[英]Function pointer inside class point to that class's member function
I am familiar with the function pointer to class member issue, which requires the signature to be ClassName::*FuncPtr
, but I have this nuanced problem where I need the function pointer to be to a containing class member:
class F
{
public:
class Container;
typedef void (Container::*FuncPtr)();
F(FuncPtr fp) : m_fp(fp) {}
void Execute() { (*this.*m_fp)(); }
private:
FuncPtr m_fp;
};
class Container
{
public:
Container() : fps(&Container::Func) { }
void Func() { }
private:
F fps;
};
所以,基本上我想創建一個 object Container
,它將在其構造函數中發送一個指向其成員函數之一的指針,指向它包含的F
object,它應該存儲 function 指針。
需要前移聲明class Container;
在F
之外。 在F
內部,它聲明了F::Container
,它是與Container
不同的類型。
此外, (*this.*m_fp)()
(或者(this->*m_fp)()
)根本不起作用,因為m_fp
期望.*
(或->*
)左側有一個Container
object , this
是指向F
object 。 因此Container
必須將其this
指針傳遞給F
的構造函數以與m_fp
一起存儲。
嘗試這個:
#include <iostream>
using namespace std;
class Container;
class F
{
public:
typedef void (Container::*FuncPtr)();
F(Container &c, FuncPtr fp) : m_c(c), m_fp(fp) {}
void Execute() { (m_c.*m_fp)(); }
private:
Container& m_c;
FuncPtr m_fp;
};
class Container
{
public:
Container() : fps(*this, &Container::Func) { }
void Func() { ... }
private:
F fps;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.