簡體   English   中英

當前類成員函數上的指針數組

[英]Array of Pointers on Member functions of current class

我嘗試創建當前類的成員函數的指針數組,但暫時沒有成功...

我已經嘗試了很多事情,這是我的代碼:

// Human.hpp

#include <iostream>

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);
};
// Human.cpp

#include "Human.hpp"

// ...

void    Human::action(std::string const & action_name, std::string const & target)
{
    std::string actionsStr[] = {"meleeAttack", "rangedAttack", "intimidatingShout"};

    typedef void (Human::*Actions)(std::string const & target);
    Actions actions[3] = {&Human::meleeAttack, &Human::rangedAttack, &Human::intimidatingShout};

    for (int i = 2; i >= 0; i--)
        if (actionsStr[i] == action_name)
        {
            actions[i](target); // there is an error HERE
            break;
        }
}

這段代碼會在編譯時產生錯誤:

main.cpp:41:23: error: called object type 'Actions' (aka 'void (Human::*)(const std::string &)') is not a function or function pointer
            actions[i](target);
            ~~~~~~~~~~^
1 error generated.

有什么好的方法呢?

for (int i = 2; i >= 0; i--)
    if (actionsStr[i] == action_name)
    {
        (this->*(actions[i]))(target);
        break;
    }

暫無
暫無

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

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