将子类作为父类传递给方法 [英] Pass child class to method as parent class
问题描述
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 的东西在我的脑海中似乎有点混乱)
I hope this example understandable enough. I tried to apply the principle of inheritance but I get these errors: (OOP stuff seems to be a little bit messed in my head)
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)
那么传递子项而不是父项的正确方法是什么?谢谢!
So what is the correct way to pass child instead of its parent? Thanks!
推荐答案
void setmethod(Method m)
的签名不正确.它必须是 void setmethod(Method* m)
以匹配您的调用.
Signature of your void setmethod(Method m)
isn't correct. It must be void setmethod(Method* m)
to match your invocation.
作为旁注,您的方法中需要一个引用或指针才能使多态性工作 - 这意味着您不能通过值将参数传递给 setmethod
并期望多态性工作.
As a side note, you need a reference or a pointer in your method for the polymorphism to work - that means that you can't pass the argument to setmethod
by value and expect the polymorphism to work.
这篇关于将子类作为父类传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!