我有一个带有两个成员函数getA
和getA2
的类,它们具有相似的作用。它们都可能在内部计算可能不同之后返回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;
}
能以某种方式完成吗?通过阅读函数指针,我不确定如何正确地在此处应用它。
最佳答案
您可以通过传递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)()
中的括号,因为运算符优先级需要它。关于c++ - C++我可以将成员函数的选择作为参数传递吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55323589/