【发布时间】:2019-03-24 12:04:12
【问题描述】:
我有一个有两个成员函数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;
}
可以以某种方式完成吗?通过阅读函数指针,我不确定如何在此处正确应用它。
【问题讨论】:
标签: c++ member-functions