介绍
大多程序员在学C++前都学过C,并且习惯于C风格(类型)转换。当写C++(程序)时,有时候我 们在使用static_cast<>和reinterpret_cast<>时可能会有点模糊。在本文中,我将说明 static_cast<>实际上做了什么,并且指出一些将会导致错误的情况。
泛型(Generic Types)
float f = 12.3;
float* pf = &f;
// static cast<>
// 成功编译, n = 12
int n = static_cast<int>(f);
// 错误,指向的类型是无关的(译注:即指针变量pf是float类型,现在要被转换为int类型)
//int* pn = static_cast<int*>(pf);
//成功编译
void* pv = static_cast<void*>(pf);
//成功编译, 但是 *pn2是无意义的内存(rubbish)
int* pn2 = static_cast<int*>(pv);
// reinterpret_cast<>
//错误,编译器知道你应该调用static_cast<>
//int i = reinterpret_cast<int>(f);
//成功编译, 但是 *pn 实际上是无意义的内存,和 *pn2一样
int* pi = reinterpret_cast<int*>(pf);
简而言之,static_cast<> 将尝试转换,举例来说,如float-到-integer,而reinterpret_cast<>简单改变编译器的意图重新考虑那个对象作为另一类型。
指针类型(Pointer Types)
指针转换有点复杂,我们将在本文的剩余部分使用下面的类:
class CBaseX
{
public:
int x;
CBaseX() { x = 10; }
void foo() { printf("CBaseX::foo() x=%d/n", x); }
};
class CBaseY
{
public:
int y;
int* py;
CBaseY() { y = 20; py = &y; }
void bar() { printf("CBaseY::bar() y=%d, *py=%d/n", 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