[英]what does in c++ for example means typedef void(Number:: *Action)(int &);
嗨,我从Web上获得了这个命令模式示例,但是有一点我不理解是typedef东西,什么是* Action resns,这里我什至没有定义此方法...这是代码示例:
#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
和其他类。
使用http://www.cdecl.org (一个非常有用的网站),并以void(Number:: *Action)(int &)
作为输入(请注意,它不处理typedefs
)可以实现以下目的:
将Action声明为指向类Number函数成员的指针(对int的引用),返回void警告:C语言中不支持-“指向类成员的指针”警告:C语言中不支持-“引用”
typedef void(Number:: *Action)(int &);
此typedef定义一个名称为Action
的类型。 Action
类型是Number
类的成员函数的成员函数指针,该成员函数的参数类型为int&
,返回类型为void
。
由于Action
是类型的名称,所以这就是为什么您在SimpleCommand
构造函数中看到此名称的原因。
SimpleCommand(Number *rec, Action act)
{ //see this ^^^^^^ - being used as type!
receiver = rec;
action = act;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.