<分区>
如何在 C++ 中正确地将父类类型转换为子类?
例如,如果我有两个类,
Atom -> Cu
(Parent) (Child)
并且我已经确定我有一个 Atom a
实际上是 Cu
的一个实例,然后我如何将 a
类型转换为Cu
对象?
到目前为止我尝试了什么:
Cu c = (Cu) a
-> No matching conversion for C-style cast from 'Atom' to 'Cu'
Cu c = Cu (a)
-> No matching conversion for functional-style cast from 'Atom' to 'Cu'
Cu c = static_cast<Cu>(a)
-> No matching conversion for static_cast from 'Atom' to 'Cu'
Cu c = dynamic_cast<Cu*>(&a)
-> 'Atom' is not polymorphic
编辑:一个(粗略的)解决方案
这是一段可以完成我所需要的工作代码:
// Overrides Atom::equals(Atom* other)
bool Cu::equals(Atom* a) {
// checks to see if a is a Cu pointer
if(other->getID() == "Cu") {
// If so, typecasts it
Cu* c = (Cu*) a;
// Checks functions specific to Cu atoms
...
}
}
编辑 2
我已将此问题标记为重复,因为 1)我读过的最好的解决方案涉及“虚拟功能”,并且 2) 这个问题现在重定向到的问题提到了它们并解释了它们为什么有用。