簡體   English   中英

Function class 內的指針指向該類的成員 function

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM