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();
}
我希望这个例子足够容易理解。我试图应用继承原则,但我得到了这些错误:(OOP 的东西在我的脑海里似乎有点乱)
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)
那么传递孩子而不是父母的正确方法是什么?谢谢!