<分区>
谁能说出 C++ 中动态转换的确切含义。 我们究竟可以在哪里使用这种动态类型转换? 这是在面试中被问到的,我对这个问题一无所知:)。
标签 c++ dynamic-cast
<分区>
谁能说出 C++ 中动态转换的确切含义。 我们究竟可以在哪里使用这种动态类型转换? 这是在面试中被问到的,我对这个问题一无所知:)。
最佳答案
dynamic_cast 是在运行时找出对象类的转换方法。
class Base
{
public:
virtual bool func1();
};
class Derived1 : Base
{
public:
virtual bool func1();
virtual bool funcDer1();
};
class Derived2 : Base
{
public:
virtual bool func1();
virtual bool funcDer2();
};
Base* pDer1 = new Derived1;
Base* pDer2 = new Derived2;
Derived2* pDerCasted = dynamic_cast<Derived2*>(pDer2);
if(pDerCasted)
{
pDerCasted->funcDer2();
}
-> We cannot call funcDer2 with pDer2 as it points to Base class
-> dynamic_cast converts the object to Derived2 footprint
-> in case it fails to do so, it returns NULL .( throws bad_cast in case of reference)
注意:通常,谨慎的 OO 设计应避免 Dynamic_cast。
关于c++ - C++ 中的动态转换到底是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1781763/