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)
那么,正确的方法是如何传递子代而不是其父代?谢谢!
Simulator() {}
替换Simulator();
。 - SomeWittyUsernameRum
。请定义它或将其变为纯虚拟函数:virtual void Rum() = 0;
- SomeWittyUsername