用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换。
1
2
主要用于层次间的上行转换和下行转换
在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;
在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全;
1
2
常量指针被转化成非常量指针,并且仍然指向原来的对象;
常量引用被转换成非常量引用,并且仍然指向原来的对象;
//常量指针转换成非常量指针
void test01(){
const int* p = NULL;
int* np = const_cast<int*>(p);
int* pp = NULL;
const int* npp = const_cast<const int*>(pp);
const int a = 10; //不能对非指针或非引用进行转换
//int b = const_cast<int>(a); }
//常量引用转换成非常量引用
void test02(){
int num = 10;
int & refNum = num;
const int& refNum2 = const_cast<const int&>(refNum);
}