我想創建這樣一個接口:
如何通過接口存儲成員函數指針
class IMother {
public:
// This getter return a map which contains a member functer pointer
virtual map<string, void (IMother::*)()> getMap() const = 0;
virtual ~IModule() {};
};
然後,創建一個孩子,並覆蓋吸氣,以返回地圖只包含Child_1成員函數指針
class Child_1 : public IMother {
private:
map<string, void (Child1::*)(int)> _map;
public:
void do_something_1(int a) {
// Something...
}
void do_something_2(int a) {
// Something...
}
virtual map<string, void (Child1::*)(int)> getMap() {
_map["do_1"] = &do_something_1;
_map["do_2"] = &do_something_2;
return _map;
}
,我想我就可以讓它工作,因爲,在我的腦海,我想Child1是IMother所以我必須編寫正確的,但我不能..
int main() {
IMother *mother = new Child_1;
// I don't know how run a method through a map
mother->getMap["do_1"](42); // Not seem to work
return 0;
}
有沒有辦法通過接口存儲成員函數指針?
使用C++ 11,可以將'override'屬性添加到'Child1 :: getMap',如果你這樣做,編譯器會警告你,你不是重寫。 – 2012-02-22 12:53:58