gpt4 book ai didi

c++ - 函数指针 + 映射 + 迭代器 + 类

转载 作者:行者123 更新时间:2023-11-28 08:08:49 25 4
gpt4 key购买 nike

我有个小问题!


class AKSH
{
private:
typedef map<string,void (AKSH::*)()> t_list;
public:
t_list list;
AKSH(){...}

};

AKSH sh;

void AKSH::doWork()
{
map<string,void (AKSH::*)()>::iterator it;
...
if(it != list.end())
{
(sh.*it->second)();
}

int main()
{
AKSH aksh;
aksh.doWork();
}

我必须生成 2 个对象(aksh、sh)。我如何将 aksh 与迭代器一起使用,或者行 (sh.*it->second) 中是否有错误?

最佳答案

你想要:(this->*(it->second))();

但是,在添加之前,阅读 this page !如果您不阅读该页面,并且继续使用指向成员函数的指针,我保证您会气急败坏。

#include <map>
#include <string>
#include <iostream>

class AKSH
{
private:
typedef std::map<std::string,void (AKSH::*)()> t_list;
const std::string name;
public:
t_list list;
void add() { std::cout << name << ": " << __FUNCTION__ << "\n"; }
void sub() { std::cout << name << ": " << __FUNCTION__ << "\n"; }
void doWork(const std::string&);
AKSH(const std::string& name) :name(name) {
list["add"] = &AKSH::add;
list["sub"] = &AKSH::sub;
}
};

AKSH sh("sh");

void AKSH::doWork(const std::string& str)
{
AKSH::t_list::iterator it;
it = list.find(str);
if(it != list.end())
{
(this->*(it->second))();
}
else
{
std::cout << name << ": No such command: " << str << "\n";
}
}
int main()
{
AKSH aksh("aksh");
aksh.doWork("add"); aksh.doWork("sub");
sh.doWork("add"); sh.doWork("sub");
sh.doWork("div"); aksh.doWork("mul");
}

关于c++ - 函数指针 + 映射 + 迭代器 + 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9606529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com