static_cast的作用:
前提:互换的两种类型必须是相关的类型,而且不针对多态
(1) 在非多态的类层次中,子孙对象指针或引用的互换
(2) 空指针与其他类型指针的呼唤
(3) 用于基本数据类型之间的转换
即,非多态的类层次之间以及基本数据类型之间的转换
注意 :
(0) static_cast 中static表示在类型转换时,是在编译时进行的,其与dynamic对应。
(1) static_cast 不能转换掉const、volatile、或者__unaligned属性
(2) static_cast 在编译期间转换,存在编译时的类型检查,检查原类型和目标类型是否能转换,不能则报错。
(3) static_cast 进行的是简单粗暴的转换,没有运行时类型检查来保证转换的安全性。
(4) 在有继承关系的对象之间转换时,尽量不要用static_cast ,而用dynamic_cast
(5)static_cast 作用于存在多态的对象之间时,由子类到父类的转换是安全的,而父类到子类的转换是不安全的。
static_cast的语法:
static_cast<type-id>(expression)说明:
(1) type_id 和 目标类型是一样的
(2) type_id 和 目标类型是引用或指针。
举例:
#include <iostream>
using namespace std;
class Base
{
public:
void BaseAAA()
{
cout<<"BaseAAA"<<endl;
}
void AAA()
{
cout<<"Base::AAA"<<endl;
}
};
class Derived : public Base
{
public:
void DerivedAAA()
{
cout<<"DerivedAAA"<<endl;
}
void AAA()
{
cout<<"Derived::AAA"<<endl;
}
};
int main()
{
Derived* pDerived = new Derived;
Base* pBase = static_cast<Base*>(pDerived); //子类到父类的转换
pBase->AAA(); //Base::AAA
pBase->BaseAAA(); //BaseAAA
pDerived = static_cast<Derived*>(pBase); //父类到子类的转换
pDerived->AAA(); //Derived::AAA
pDerived->BaseAAA(); //BaseAAA
pDerived->DerivedAAA();//DerivedAAA
void* pVoid = static_cast<void*>(pDerived);//空指针与其他类型指针互换
pDerived = static_cast<Derived*>(pVoid);
pDerived->AAA(); //Derived::AAA
pDerived->BaseAAA(); //BaseAAA
pDerived->DerivedAAA();//DerivedAAA
double dNum = 1.256; //用于基本数据类型之间的转换
int nNum = static_cast<int>(dNum);
cout<<nNum<<endl; //1
system("pause");
return 1;
}
本文详细介绍了C++中的static_cast操作符的使用方法及其注意事项。主要内容包括static_cast的基本用途、转换限制及转换过程中的安全性问题。此外,还通过实例展示了static_cast在不同场景下的应用。
1246

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



