[英]C++ Can I pass the choice of member function as argument?
我有一個具有兩個成員函數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;
}
能以某種方式完成嗎? 通過閱讀函數指針,我不確定如何正確地在此處應用它。
您可以通過將指針傳遞給成員函數來進行所需的參數化。
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)()
中的括號,因為運算符優先級需要它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.