c++ - 例如,在 C++ 中的意思是 typedef void(Number::*Action)(int &);

标签 c++ typedef

您好,我有这个来自网络的命令模式示例,但是我不明白 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/

相关文章:

c - typedef 结构中的指针

c++ - g++ 创建静态库 : could not read the symbols archive has no index

c++ - 传递给 main() 的 argc 和 argv 值是如何设置的?

c++ - 有什么方法可以检测 QObject 是否属于 "dead"QThread?

c++ - 如何从 USB Token 的公钥/私钥对获取 CKA_ID?

c++ - std::result_of 应用于 const 重载方法

c++ - 我可以用 C++ "forward declare"做什么?

C: typedef union

c++ - 用最近定义的结构替换前向声明的结构

c++ - 'reference' typedef 的行为究竟如何?