显式类型转换也叫做强制类型转换,强制转换的操作符包括:static_cast、dynamic_cast、const_cast、reinterpret_cast。
(1)static_cast。C++中所有的隐式类型转换都可以通过此运算符完成,尤其对于会损失精度的大算术类型赋值小算术类型的情况,有了static_cast描述符,编译器便会认为这是条正常语句,而不会报告警告信息;另一个典型的应用场景就是对void 类型指针的类型定义。
const char *str=static_cast<const char *>(malloc(sizeof(char)*10));
int a;
double b=12.33456;
a=static_cast<int>(b);
cout<<"a:"<<a<<endl;
(2)const_cast。编码过程中总有如此情景:一个函数形参类型为非const指针,但是你又不得不传入一个const类型的指针,所以为了解决这个问题,const_cast运算符出现,去掉指针的实参的const属性。
int string_copy(char *str)
{
char c=str[1];
str[2]='A';//运行时通过!
cout<<str[2]<<endl;
return 1;
}
int main()
{
const char *str=static_cast<const char *>(malloc(sizeof(char)*10));
const char * pstr=str;
string_copy(const_cast<char *>(pstr));
}
(3)reinterpret_cast。为操作数的为模式提供较低层次的重新解释:
int c=0x01020304;
int *ip=&c;
char *cp=reinterpret_cast<char *>(ip);
cout<<int(*cp)<<endl;
(4)dynamic_cast。将基类的指针转换为子类的指针。
class A
{
public:
int a;
virtual int print() {return a;}
};
class B:public A
{
int b;
int print(){return a;}
};
class C:public A
{
int c;
int print(){return a;}
};
int main()
{
B b;
A *pa=&b;
C *pb=dynamic_cast<B *>(pa);//如果强制转换成C类型指针,运行时会出错!!
pb->a=12;
cout<<pb->a<<endl;
return 0;
}
小结:强制转换使C++逐渐向C“靠拢”,默认程序员会清楚自己在干什么,但是这绝对不是程序员想要的!