
/**//**********************************************************
static_cast<>揭密
简而言之,static_cast<> 将尝试转换,举例来说,如float-到-integer,
而reinterpret_cast<>简单改变编译器的意图重新考虑那个对象作为另一类型。
http://www.vckbase.com/document/viewdoc/?id=1651
*********************************************************/
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;
};
void main()
...{
int a = 100;
float b = 12.324;
a = static_cast<int>(b); //正确.成功将 float 转换成了 int
cout<<a<<endl;
int a = 100;
int *p = &a;
float *b = static_cast<float*>(p); //错,这里不能将int*转换成float*
int a = 100;
void *p = &a;
float *b = static_cast<float*>(p); //正确.可以将void*转换成float*
CBaseX *pX = new CBaseX();
CBaseY *pY1 = static_cast<CBaseY*>(pX); //错误,不能将CBaseX*转换成CBaseY*
CBaseX *pX = new CBaseX();
CBaseY *pY1 = reinterpret_cast<CBaseY*>(pX); //正确. “欺骗”编译器
pY1->bar(); //崩溃
//正如我们在泛型例子中所认识到的,如果你尝试转换一个对象到另一个
//无关的类static_cast<>将失败,而reinterpret_cast<>就总是成功“欺骗”
//编译器:那个对象就是那个无关类
}
本文探讨了static_cast与reinterpret_cast的区别及应用场景。通过实例演示了两种类型转换如何在C++中工作,包括从float到int的基本类型转换,以及指针间的转换。同时对比了它们在对象类型转换上的表现。
4798

被折叠的 条评论
为什么被折叠?



