您好,我有这个来自网络的命令模式示例,但是我不明白 typedef 的东西,这里的 * Action represns 是什么,我什至没有定义这个方法...这是代码示例:
#include <iostream>
#include <vector>
using namespace std;
class Number
{
public:
void dubble(int &value)
{
value *= 2;
}
};
class Command
{
public:
virtual void execute(int &) = 0;
};
class SimpleCommand: public Command
{
typedef void(Number:: *Action)(int &);
Number *receiver;
Action action;
public:
SimpleCommand(Number *rec, Action act)
{
receiver = rec;
action = act;
}
/*virtual*/void execute(int &num)
{
(receiver-> *action)(num);
}
};
class MacroCommand: public Command
{
vector < Command * > list;
public:
void add(Command *cmd)
{
list.push_back(cmd);
}
/*virtual*/void execute(int &num)
{
for (int i = 0; i < list.size(); i++)
list[i]->execute(num);
}
};
int main()
{
Number object;
Command *commands[3];
commands[0] = &SimpleCommand(&object, &Number::dubble);
MacroCommand two;
two.add(commands[0]);
two.add(commands[0]);
commands[1] = &two;
MacroCommand four;
four.add(&two);
four.add(&two);
commands[2] = &four;
int num, index;
while (true)
{
cout << "Enter number selection (0=2x 1=4x 2=16x): ";
cin >> num >> index;
commands[index]->execute(num);
cout << " " << num << '\n';
}
}
最佳答案
typedef
定义了一个指向函数的指针,该函数是类 Number
的一个方法并接受一个 int
。
请注意,当您提供实际功能时,它是 dubble
,并且已实现。但是您可以添加更多,当您这样做时 - 您只会更改 Number
类,而不是 Command
和其他类。
关于c++ - 例如,在 C++ 中的意思是 typedef void(Number::*Action)(int &);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5308598/