【发布时间】:2011-10-14 07:30:52
【问题描述】:
我知道 static_cast 可以在基数和派生以及派生和基数之间转换。 dynamic_cast 将检查结果对象是否为“完整”对象。
dynamic_cast 使用 RTTI 功能。但是 static_cast 是如何工作的呢? “兼容类型”是什么意思?
我的问题实际上是关于兼容类型的含义。但我很高兴从帖子中学到了一些东西。此示例演示了编译器如何解释兼容类型。最后几行是最有趣的。注意有趣的结果。
#include <iostream>
#include <exception>
using namespace std;
class CBase { virtual void dummy() {} };
class CDerived: public CBase { public: CDerived() : a(20) {} int a; };
class CDerived2: public CBase { public: CDerived2() : b(7) {} int b; };
class CDerived3: public CBase { public: CDerived3() : c('A') {} char c; };
class CNotDerived { int doit() const { return 9; } };
int main () {
try {
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd;
CNotDerived* pnot = new CNotDerived;
CDerived2* pd2 = 0;
CDerived2* pdx = new CDerived2;
CDerived3* pd3 = 0;
pd = dynamic_cast<CDerived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast" << endl; //ok
pd = dynamic_cast<CDerived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast" << endl; //null ptr here
pd = static_cast<CDerived*>(pbb); //non-null pointer returned (not really what you want)
if (pd==0) cout << "Null pointer on third type-cast" << endl;
// pd = dynamic_cast(pnot); //error C2683: 'dynamic_cast' : 'CNotDerived' 不是多态类型 // if (pnot==0) cout
// pd = static_cast(pnot); //错误 C2440: 'static_cast' : 无法从 'CNotDerived *' 转换为 'CDerived *' // if (pnot==0) cout
//below lines compiled with ms vs2008 - I believe compiler SHOULD have flagged below as an error - but did not.
pd2 = static_cast<CDerived2*>(pba); //compiles ok but obviously incorrect
if (pd2==0) cout << "Null pointer on fourth type-cast" << endl;
cout << pd2->b << endl; //compiler had decided to give us CDerived->a value! Incorrect.
pd2 = static_cast<CDerived2*>(pdx); //compiles ok
if (pd2==0) cout << "Null pointer on fourth type-cast" << endl;
cout << pd2->b << endl; //gives correct value for b (7)
pd3 = static_cast<CDerived2*>(pdx); //error C2440: '=' : cannot convert from 'CDerived2 *' to 'CDerived3 *'
if (pd3==0) cout << "Null pointer on fourth type-cast" << endl;
cout << pd3->c << endl;
} catch (exception& e) {
cout << "Exception: " << e.what();
}
return 0;
}
【问题讨论】: