簡體   English   中英

創建指向成員函數的指針數組

[英]Creating an Array of pointers to member functions

簡而言之,我嘗試搜索如何執行此操作,但我似乎遺漏了一些東西。 我的問題的一個限制條件是:Human.h 無法更改。 我們必須根據所獲得的進行操作。 我還被告知創建指向成員的指針數組,以決定需要調用哪個 function。

這是我所擁有的:

人類.h

class Human
{
private:
    void meleeAttack(std::string const& target);
    void rangedAttack(std::string const& target);
    void intimidatingShout(std::string const& target);
public:
    void action(std::string const& action_name, std::string const& target);
};

人類.cpp

#include "Human.h"

typedef void (Human::* Human_mem_fnPtr)(std::string target);

void Human::meleeAttack(std::string const& target)
{
    std::cout << "Melee Attack performed on " << target << "!\n";
}

void Human::rangedAttack(std::string const& target)
{
    std::cout << "Ranged Attack performed on " << target << "!\n";
}

void Human::intimidatingShout(std::string const& target)
{
    std::cout << "Shout performed on " << target << "!\n";
}

void Human::action(std::string const& action_name, std::string const& target)
{
    //error on initialization--expression must be an lvalue or function designation--but they ARE func designations...
    Human_mem_fnPtr fnPtr[] = {&Human::meleeAttack(target), &Human::rangedAttack(target), &Human::intimidatingShout(target)}; 
}

從我在網上找到的內容來看,我正在朝着正確的方向前進。 我錯過了什么?

幾點:

  • 使用std::function<>模板 class 使指向函數的指針變得更加容易。
  • 現在使用舊式數組並不是最好的選擇。

mapunordered_map將是更好的選擇,其定義如下:

using ActionMap = std::unordered_map<const std::string, std::function<void(const std::string&)>;

將您的函數添加到此 map 時,您將使用如下內容:

mActionMap["rangedAttack"] =  std::mem_fn(&Human::rangedAttack);

這將為您提供一個更干凈、更易於維護的選項,並且應該可以干凈地編譯。

請注意,需要std::mem_fn來包裝 class 的成員 function。

編輯:根據您在下面的評論,我仍然建議盡可能多地使用現代 C++ 結構。

using ActionFunc = std::function<void(const std::string&)>;

然后:

ActionFunc actions[] = { std::mem_fn(&Human::rangedAttack), ...}

或者:

std::array<ActionFunc> actions =...

暫無
暫無

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

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