static_cast运算符是标准c++中的强制类型转换运算符。原先的c语言中是存在类型转换的,如int型直接转换为float型,为什么需要引入新的类型转换?目的是为了克服旧式c语言中类型转换的缺陷。旧式的类型转换是很强的一种语法,带来的后果是引入很多不易察觉的错误。static_cast比旧式的类型转换更具体,更安全,类型转换的错误能在编译期间发现。例如,const类型转换为非const类型在编译期间被认为是一个语法错误。
#include<iostream>
using namespace std ;
class animal {
public:
void print(void) const{
cout<<"this is a animal"<<endl;}
};
class fish : public animal{
public:
void print(void) const{
cout <<"this is a fish"<<endl;
}
};
void test(animal *animalPtr)
{
fish * fishPtr;
fishPtr=static_cast<fish *>(animalPtr);
//可以用static_cast进行基类向派生类的转换
// fishPtr= animalPtr;
//无效的类型转换
fishPtr->print();
animalPtr=fishPtr;
animalPtr->print();
} ;
int main()
{
animal theanimal;
test(&theanimal);
cin.get();
}
//输出的结果是
this is a fish
this is a animal