static_cast<>揭密
2007-03-15 21:54:22 来源:WEB开发网核心提示: class CBaseX{public:int x;CBaseX() { x = 10; }void foo() { printf("CBaseX::foo() x=%d", x); }};class CBaseY{public:int y;int* py;CBaseY
class CBaseX
{
public:
int x;
CBaseX() { x = 10; }
void foo() { printf("CBaseX::foo() x=%d
", x); }
};
class CBaseY
{
public:
int y;
int* py;
CBaseY() { y = 20; py = &y; }
void bar() { printf("CBaseY::bar() y=%d, *py=%d
", y, *py);
}
};
class CDerived : public CBaseX, public CBaseY
{
public:
int z;
};
情况1:两个无关的类之间的转换 // Convert between CBaseX* and CBaseY*
// CBaseX* 和 CBaseY*之间的转换
CBaseX* pX = new CBaseX();
// Error, types pointed to are unrelated
// 错误, 类型指向是无关的
// CBaseY* pY1 = static_cast<CBaseY*>(pX);
// Compile OK, but pY2 is not CBaseX
// 成功编译, 但是 pY2 不是CBaseX
CBaseY* pY2 = reinterpret_cast<CBaseY*>(pX);
// System crash!!
// 系统崩溃!!
// pY2->bar();
正如我们在泛型例子中所认识到的,如果你尝试转换一个对象到另一个无关的类static_cast<>将失败,而reinterpret_cast<>就总是成功“欺骗”编译器:那个对象就是那个无关类。情况2:转换到相关的类
1. CDerived* pD = new CDerived();
2. printf("CDerived* pD = %x
", (int)pD);
3.
4. // static_cast<> CDerived* -> CBaseY* -> CDerived*
//成功编译,隐式static_cast<>转换
5. CBaseY* pY1 = pD;
6. printf("CBaseY* pY1 = %x
", (int)pY1);
// 成功编译, 现在 pD1 = pD
7. CDerived* pD1 = static_cast<CDerived*>(pY1);
8. printf("CDerived* pD1 = %x
", (int)pD1);
9.
10. // reinterpret_cast
// 成功编译, 但是 pY2 不是 CBaseY*
11. CBaseY* pY2 = reinterpret_cast<CBaseY*>(pD);
12. printf("CBaseY* pY2 = %x
", (int)pY2);
13.
14. // 无关的 static_cast<>
15. CBaseY* pY3 = new CBaseY();
16. printf("CBaseY* pY3 = %x
", (int)pY3);
// 成功编译,尽管 pY3 只是一个 "新 CBaseY()"
17. CDerived* pD3 = static_cast<CDerived*>(pY3);
18. printf("CDerived* pD3 = %x
", (int)pD3);
---------------------- 输出 ---------------------------
CDerived* pD = 392fb8
CBaseY* pY1 = 392fbc
CDerived* pD1 = 392fb8
CBaseY* pY2 = 392fb8
CBaseY* pY3 = 390ff0
CDerived* pD3 = 390fec
注意:在将CDerived*用隐式 static_cast<>转换到CBaseY*(第5行)时,结果是(指向)CDerived*(的指针向后) 偏移了4(个字节)(译注:4为int类型在内存中所占字节数)。为了知道static_cast<> 实际如何,我们不得不要来看一下CDerived的内存布局。
更多精彩
赞助商链接