statoc_cast: 该操作符用于非多态类型的转换,任何标准转换都可以使用他,即static_cast可以把int转换为 double,但不能把两个不相关的类对象进行转换,比如类A不能转换为一个不相关的类B类型。static_cast本质上是传统c语言强制转换的替代 品。
两种不合法:
1.
char* p=new char[5];
unsigned long l=static_cast(p); //Error : cannot convert from 'char *' to 'unsigned long'
2.
class A{};
A a;
unsigned long l=static_cast(a); //Error :'static_cast' : cannot convert from 'A' to 'unsigned long'
const_cast:
可以将const类型转换为非const,也可以将非const转换为const;可以将volatile转换成非volatile,也可以将非volatile转换成volatile。
const_cast多用于指针,存在以下情况:
1.
const int x=1;
int* p=&x; //Error : 'initializing' : cannot convert from 'const int *' to 'int *'
2.
const int x=1;int* p=const_cast(&x); //ok 3.
int x=1;
const int* p=const_cast(&x); //ok
4.
int x=1;
const int* p=&x; //ok
5.
volatile int x;
int* p=&x; //Error: 'initializing' : cannot convert from 'volatile int *' to 'int *'