【问题标题】:C++ Can I pass the choice of member function as argument?C++ 我可以将成员函数的选择作为参数传递吗?
【发布时间】:2019-03-24 12:04:12
【问题描述】:

我有一个有两个成员函数getAgetA2 的类,它们做类似的事情。在可能不同的内部计算之后,它们都返回一个 int。

在函数printStuff 中我调用了两者,但实际上我只想调用其中一个,但没有在printStuff 中命名它。我想以某种方式向printStuff 提供A 类的哪个成员函数在其主体中用作printStuff 的参数的信息。

class A {
public:
  A(int a) : m_a(a) {;}
  int getA() {
    return m_a;
  };
  int getA2() {
    return 2*m_a;
  };

private:
  int m_a = 0;

};

void printStuff(/*tell me which member fcn to use*/) {
  A class_a(5);

  //I actually just want to call the last of the 2 lines, but define somehow
  //as an argument of printStuff which member is called
  cout << "interesting value is: " << class_a.getA() << endl;
  cout << "interesting value is: " << class_a.getA2() << endl;
  cout << "interesting value is: " << /*call member fcn on class_a*/ << endl;
}

int functional () {

  printStuff(/*use getA2*/); //I want to decide HERE if getA or getA2 is used in printStuff
  return 0;
}

可以以某种方式完成吗?通过阅读函数指针,我不确定如何在此处正确应用它。

【问题讨论】:

    标签: c++ member-functions


    【解决方案1】:

    您可以通过传递pointer to a member function 进行所需的参数化。

    void printStuff( int (A::* getter)() ) {
      A class_a(5);
    
      cout << "interesting value is: " << (a.*getter)() << endl;
    }
    
    // in main
    printStuff(&A::getA2);
    

    声明符语法int (A::* getter)() 在真正的C++ 方式中有点奇怪,但这就是在函数签名中使用原始指向成员函数的方式。类型别名可能会稍微简化语法,因此请牢记这一点。我认为&amp;A::getA2 是不言自明的。

    还要注意(a.*getter)() 中的括号,因为运算符优先级需要它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      • 2017-12-01
      相关资源
      最近更新 更多