【发布时间】:2011-07-15 20:39:10
【问题描述】:
如何转换为派生类?以下方法都给出以下错误:
无法从 BaseType 转换为 DerivedType。没有构造函数可以接受 源类型或构造函数重载决议不明确。
BaseType m_baseType;
DerivedType m_derivedType = m_baseType; // gives same error
DerivedType m_derivedType = (DerivedType)m_baseType; // gives same error
DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error
【问题讨论】:
-
我不相信最后一个给出了同样的错误。
-
你确定你的 DerivedType 继承自 BaseType。你能发布更多代码吗?
-
如果您有任何 C# 或 Java 语言背景,您应该注意动态类型信息仅在您有指针时才真正使用(例如 BaseType *b = new DerivedType())。否则,你最终会被切片。
-
一开始你不应该这样做。这就是您收到错误的原因。正确完成后(通过 dynamic_cast),结果应该是 NULL 或异常。你真正想做什么?
-
你不能这样做,因为 BaseType 不是 DerivedType。您不能将 Animal 转换为 Dog,但可以将 Dog* 转换为 Animal*。
标签: c++ inheritance