嗨假設我有這樣調用從基類派生類的功能,無需使用虛擬函數
// base class
class A {
public:
int CallMyFct(PtrToFCT what){
return what(10);
}
};
class B : public A {
int myInt;
public:
B():myInt(10){}
int myFct1(int val){
return myInt+val;
}
int myFct2(int val){
return myInt*2+val;
}
void Call(void){
int rez1=CallMyFct(&myFct1);
if (rez1!=20)
cout << "You are wrong" << endl;
int rez2=CallMyFct(&myFct2);
if (rez2!=30)
cout << "You are wrong" << endl;
}
};
代碼現在我需要調用這些MyFct1,MyFct2等從基類,但我不能使用虛擬功能。所以它就像繼承的倒置一樣。我不知道這是否可能。你認爲mem_fun或其他適配器功能可以在這裏工作嗎?
我實際上需要弄清楚什麼是PtrToFCT,以及如何在CallMyFCT中傳遞myFct1。
感謝
[CRTP(https://secure.wikimedia.org/wikipedia/en/wiki/Curiously_recurring_template_pattern)可以幫助 – rlduffy