static_cast比较接近于C语言中的强制转换,多用于不同的基本数据类型的转换:
char c1 = 0; int i = static_cast(c1); char c2 = static_cast (i);
他可以将空指针转换为目标类型的指针,或反之:
int i =0; int *pa = &i; void *pv = static_cast(pa); int *pi = static_cast (pv);
但不能对不同类型的指针进行转换:
int i =0; int *pa = &i; char *pc = static_cast(pa); //编译报错:invalid static_cast from type 'int*' to type 'char* long *pl = static_cast (pa); //编译报错:invalid static_cast from type 'int*' to type 'long int*'
更不能将整数转换为指针或反之:
int i =0; int *pa = &i; char *pc = static_cast(i); //编译报错:invalid static_cast from type 'int' to type 'char*' i = static_cast (pa); //编译报错:invalid static_cast from type 'int*' to type 'int'
对于自定义类型,如果类定义转型运算符,那么也可以通过static_cast对类对象进行转型:
#includeusing namespace std; class A{ public: operator int() { return 1; } operator char() { return 'a'; } }; int main() { A a; int ai = static_cast (a); char ac = static_cast (a); cout<<"ai="<
对于自定义类型的指针,通过static_cast,将派生类指针转换为基类指针是安全的;反之,将基类指针转换为派生类指针是不安全的(建议类指针之间的转换都通过dynamic_cast进行)。



