【发布时间】:2021-11-17 17:52:56
【问题描述】:
在派生类Derived的虚方法create()中,我返回一个HelpDerived类型的结构。但是,由于我必须将方法的返回类型设置为HelpBase,我发现我需要将返回的对象转换回类型HelpDerived。
以下是我的案例。
#include <iostream>
struct HelpBase {
int a = 0;
virtual void output() {}
};
struct HelpDerived : HelpBase {
int b = 0;
void output() override {}
};
class Base {
public:
virtual HelpBase create() = 0;
};
class Derived : public Base {
public:
HelpBase create() override;
};
HelpBase Derived::create() {
HelpDerived d;
d.a = 1;
d.b = 2;
return d;
}
int main() {
Derived d;
auto based = d.create();
HelpDerived derived = dynamic_cast<HelpDerived &>(based);
std::cout << derived.a << std::endl;
}
当我运行上面的代码时,我得到了错误
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
Abort trap: 6
我对 C++ 中的对象和强制转换有什么误解?为什么这个方法不起作用?
我能做些什么来解决这个问题?
【问题讨论】:
-
您有一个
HelpBase类型的对象,而不是HelpDerived- 我猜您对在create函数中执行的对象切片感到困惑? -
多态性应该适用于指针或引用,否则你会受到对象切片的影响。
-
这能回答你的问题吗? What is object slicing?
-
在
Derived::create函数中,当您返回d时,您将获得slice 对象,只剩下返回的HelpBase对象。变量based是一个HelpBase对象,一旦在create函数中使用,就无法取回原来的HelpDerived对象。 -
谢谢,现在我至少明白是什么导致了我的问题。但我仍然不确定如何解决它。我应该让
create方法返回一个指向HelpBase对象的指针吗?
标签: c++ inheritance casting