C++ 我可以将成员函数的选择作为参数传递吗?

C++ Can I pass the choice of member function as argument?

我有一个 class,它有两个成员函数 getAgetA2,做类似的事情。它们都是 return 经过内部计算后可能不同的 int。

在函数printStuff中我调用了两个,但实际上我只想调用其中一个,但没有在printStuff中命名它。我想给 printStuff class 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;
}

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

您可以通过传递 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++ 风格中有点不靠谱,但这就是您在函数签名中使用原始指向成员函数的方式。类型别名可能会稍微简化语法,因此值得牢记这一点。我认为 &A::getA2 是不言自明的。

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