我有点问题!
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-&gt; second)?
答案 0 :(得分:1)
您想:(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");
}
答案 1 :(得分:0)
我认为这应该是
#include <iostream>
#include <map>
using namespace std;
class AKSH
{
private:
typedef map<string,void (AKSH::*)()> t_list;
public:
t_list list;
AKSH(){}
void doWork();
};
AKSH sh;
void AKSH::doWork()
{
map<string,void (AKSH::*)()>::iterator it;
if(it != list.end())
{
// here it comes.
(this->*(it->second))();
}
}
int main()
{
AKSH aksh;
aksh.doWork();
}