簡體   English   中英

如何將結構函數指針分配給結構函數

[英]How to assign a struct function pointer to a struct function

我有一個結構Game ,帶有一個名為onBegin的函數指針

struct Game {
  // ...
  void (*onBegin)(Game&);
  // ...
};

我試圖做的是允許用戶創建自己的onBegin函數,他們可以在其中說

void CustomFunc(Game& g) {
  // Do something
}

Game g = Game();
g.onBegin = *CustomFunc;

我試圖做的是創建一個函數,然后將指針onBegin設置為指向該默認函數。

struct Game {
public:
  void (*onBegin)(Game&);
private:
  void defualtOnBegin(Game&);
};

// In the constructor
Game::Game() {
  // ...
  this->onBegin = this->defaultOnBegin; // This is what is giving me the error
}

我收到錯誤: a pointer to a bound function may only be used to call the function並且不知道這里出了什么問題。

我試圖做的是允許用戶創建自己的 onBegin 函數......

您可以通過不同的方式實現這一點,但是當您想要使用函數指針方法時,您可能希望使用std::function ,例如:

#include <iostream>
#include <functional>

struct Game {
    public:
        Game(std::function<void(Game&)> customOnBeginFnc = nullptr) {
            if(customOnBeginFnc) {
                customOnBeginFnc(*this);
            } else {
                defaultOnBegin(*this);
            }
        }

    private:
        void defaultOnBegin(Game&) {
            std::cout << "Default 'onBegin'\n";
        }
};

void customOnBegin(Game&) {
    std::cout << "Custom 'onBegin'\n";
}

int main() {

    {
        std::cout << "Starting a 'default' game...\n";
        Game g;
    }

    {
        std::cout << "Starting a 'customized' game...\n";
        Game g(customOnBegin);
    }
}

在這里運行它。

這種方法的優點是您不僅可以使用自由函數,還可以通過 lambda 或std::bind將成員函數綁定到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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