class Method {
public:
virtual void Rum();
};
class Euler : public Method {
virtual void Rum() {
printf("ahoj\n");
}
};
class Kutta : public Method {
virtual void Rum() {
printf("ahoj2\n");
}
};
class Simulator {
public:
Method *pointer;
Simulator();
void setmethod(Method m) { pointer = &m; }
};
int main() {
Simulator s;
s.setmethod(new Kutta());
s.pointer->Rum();
s.setmethod(new Euler());
s.pointer->Rum();
}
我希望這個例子足夠容易理解。我嘗試應用繼承的原則,但我得到這些錯誤:(面向對象的東西似乎有點在我的腦海混亂)把子類傳給父類的方法
prog.cpp: In function ‘int main()’:
prog.cpp:26: error: no matching function for call to ‘Simulator::setmethod(Kutta*)’
prog.cpp:21: note: candidates are: void Simulator::setmethod(Method)
prog.cpp:28: error: no matching function for call to ‘Simulator::setmethod(Euler*)’
prog.cpp:21: note: candidates are: void Simulator::setmethod(Method)
那麼什麼是合格的,而不是父子正確的方法是什麼?謝謝!
\ *打哈欠\ *切片 –