【问题标题】:what does in c++ for example means typedef void(Number:: *Action)(int &);例如,在 c++ 中的意思是 typedef void(Number:: *Action)(int &);
【发布时间】:2011-07-15 13:57:38
【问题描述】:

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

【问题讨论】:

标签: c++ typedef


【解决方案1】:

typedef 定义了一个指向函数的指针,该函数是 Number 类的方法并接受 int

注意,当你提供一个实际的函数时,它是dubble,它是被实现的。但是你可以添加更多,当你这样做时 - 你只会更改 Number 类,而不是 Command 和其他。

【讨论】:

  • 但是为什么我需要 typedef 呢?我不能只声明指向函数的指针吗?我也不明白示例中的 Action 类是什么?我没有定义任何动作类
  • @user63898:我对您的问题投了反对票,因为您在提出进一步问题之前没有阅读所有答案!
  • 许多人发现指向成员语法的指针有些难以阅读; typedef 简化了它。
【解决方案2】:
 typedef void(Number:: *Action)(int &);

这个 typedef 定义了一个名为 Action 的类型。 Action 类型是一个成员函数指针,指向类Number 的成员函数,其参数类型为int&amp;,返回类型为void

由于Action 是类型的名称,这就是您在SimpleCommand 的构造函数中看到此名称的原因。

SimpleCommand(Number *rec, Action act)
{               //see this ^^^^^^ - being used as type!
    receiver = rec;
    action = act;
}

【讨论】:

    【解决方案3】:

    使用http://www.cdecl.org(一个非常有用的网站)和void(Number:: *Action)(int &amp;)作为输入(注意它不处理typedefs)给出了这个:

    将Action声明为指向成员的指针 类 Number 函数(参考 int) 返回 void 警告: C 中不支持 -- '指向成员的指针 类的警告:C 中不支持 -- '参考'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-03
      • 2014-04-22
      • 2018-05-05
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      相关资源
      最近更新 更多