我有下面的類層次結構:爲什麼C風格的演員表現不同於dynamic_cast?
class IControl
{
virtual void SomeMethod() = 0; // Just to make IControl polymorphic.
};
class ControlBase
{
public:
virtual int GetType() = 0;
};
class ControlImpl : public ControlBase, public IControl
{
public:
virtual void SomeMethod() { }
virtual int GetType()
{
return 1;
}
};
我有一個ICONTROL抽象類和ControlBase類。 ControlBase類不會從IControl繼承,但我知道每個IControl實現都將從ControlBase派生。
我有下面的測試代碼中,我與施放ICONTROL引用到ControlBase(因爲我知道它提煉出來的)的dynamic_cast,也與C風格投:
int main()
{
ControlImpl stb;
IControl& control = stb;
ControlBase& testCB1 = dynamic_cast<ControlBase&>(control);
ControlBase& testCB2 = (ControlBase&)control;
ControlBase* testCB3 = (ControlBase*)&control;
std::cout << &testCB1 << std::endl;
std::cout << &testCB2 << std::endl;
std::cout << testCB3 << std::endl;
std::cout << std::endl;
std::cout << testCB1.GetType() << std::endl; // This properly prints "1".
std::cout << testCB2.GetType() << std::endl; // This prints some random number.
std::cout << testCB3->GetType() << std::endl; // This prints some random number.
}
只有dynamic_cast能夠正常工作,另外兩個強制轉回的內存地址略有不同,GetType()函數會返回不正確的值。
這是什麼原因? C風格演員是否最終使用reinterpret_cast?它與多態對象如何在內存中對齊有關?
可能重複[何時應使用靜態\ _cast,動態\ _cast和reinterpret \ _cast?](http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and -reinterpre-cast-be-used) –
我已經看到了這個問題並閱讀了答案(以及關於此主題的其他答案)。但對我而言,這仍然不清楚爲什麼在這個具體情景中會發生這種情況,這就是爲什麼我發佈了一個單獨的問題。 –
請注意'ControlBase * testCB3 = static_cast(&control);'和'ControlBase * testCB4 = static_cast (&control);'之間存在差異。後者不調用UB(並且爲'GetType()'測試正確地生成'1')。 –
dyp