在 C++ 中将父项 class 类型转换为子项
Typecasting a parent class as a child in C++
如何在 C++ 中正确地将父 class 类型转换为子 class?
例如,如果我有两个 classes,
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) 我读过的最佳解决方案涉及 "virtual functions",以及
2)这个问题现在重定向到的问题提到了它们并解释了它们为什么有用。
I've identified that I have an Atom a
that is actually an instance of Cu
这在 C++ 中绝对不是真的。
所以……
how [do] I typecast a
to a Cu
object?
…你不能。
从父级到子级的动态转换仅在指针级别有效。由于声明为 Cu var;
的变量为 Cu
对象分配 恰好 足够 space,因此它不适合 Atom
或其他东西别的。但是,Cu* var;
为指针对象分配空间,从技术上讲,它可以是指向任何东西的指针,因此在验证 Atom*
类型的对象实际上是指向 Cu
的指针之后,您可以安全地 dynamic_cast<Cu*>
该值。您可以阅读 dynamic_cast
的详细信息 here,特别是关于转换失败会发生什么的部分。
您只能将 指针 转换为派生的 class 对象。不是对象类型本身。
你最后一次尝试最接近这个(你有效地将指向父 class 的指针转换为指向子 class 的指针)但我猜编译器检测到该对象不能多态(如果在堆上声明 Atom a
就是这种情况)
Atom * a = new Cu;
Cu * c = dynamic_cast<Cu*>(a);
狗永远是动物,但动物不总是狗。
child class 可以有变量 and/or 方法 parent class 不 have.I 相信你可以使用指针来转换它。
如何在 C++ 中正确地将父 class 类型转换为子 class?
例如,如果我有两个 classes,
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) 我读过的最佳解决方案涉及 "virtual functions",以及 2)这个问题现在重定向到的问题提到了它们并解释了它们为什么有用。
I've identified that I have an
Atom a
that is actually an instance ofCu
这在 C++ 中绝对不是真的。
所以……
how [do] I typecast
a
to aCu
object?
…你不能。
从父级到子级的动态转换仅在指针级别有效。由于声明为 Cu var;
的变量为 Cu
对象分配 恰好 足够 space,因此它不适合 Atom
或其他东西别的。但是,Cu* var;
为指针对象分配空间,从技术上讲,它可以是指向任何东西的指针,因此在验证 Atom*
类型的对象实际上是指向 Cu
的指针之后,您可以安全地 dynamic_cast<Cu*>
该值。您可以阅读 dynamic_cast
的详细信息 here,特别是关于转换失败会发生什么的部分。
您只能将 指针 转换为派生的 class 对象。不是对象类型本身。
你最后一次尝试最接近这个(你有效地将指向父 class 的指针转换为指向子 class 的指针)但我猜编译器检测到该对象不能多态(如果在堆上声明 Atom a
就是这种情况)
Atom * a = new Cu;
Cu * c = dynamic_cast<Cu*>(a);
狗永远是动物,但动物不总是狗。 child class 可以有变量 and/or 方法 parent class 不 have.I 相信你可以使用指针来转换它。