I am trying to get my Base class instance and cast it to the derived class type. Since I can only get a const reference of my base class instance, I struggle to get it cast correctly. Does anyone have an idea?
class Base
{
};
class Derived : public Base
{
};
Base someBaseInstance;
const Base& GetBase()
{
return someBaseInstance;
}
int main()
{
Derived& derived = static_cast<Base&>(GetBase());
return 0;
}
答案 0 :(得分:0)
您必须将您的实例声明为Derived
对象。它可以作为Base
引用和传递,但必须声明为Derived
:
Derived someDerivedInstance;
另外,要在Base
和Derived
之间进行转换,您应该使用dynamic_cast<>
:
Derived &derived = dynamic_cast<Derived&>(GetBase());