1.static_cast //static_cast用于内置的数据类型,具有继承关系的指针或者引用,不进行安全检查,自转父,父转子都可以。
2.dynamic_cast 通常在基类与派生类转换时使用
只能转换具有继承关系的指针或引用, 进行安全检 查,只能由子类转换成基类。
3.const_cast 主要针对const转换
4.reinterpret_cast 用于进行没有任何关联之间的转换,比如一个字符串指针转换为一个整形数
dynamic_cast
子类指针转换成父类指针,大转换成小,安全
父类指针转换成子类指针,小转换成大,不安全
// 类型转换.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
//static_cast
class Building {
};
class Animal
{
};
class Cat :public Animal
{
};
//static_cast
void test01()
{
int a = 97;
char c = static_cast<char>(a);
cout << c << endl;//a
//基础类型指针
//int *p = NULL;
//char *sp = static_cast<char*>(p);
//对象指针
// *p = NULL;
//Animal *animal = static_cast<Animal*>(p);
//转换具有继承关系的对象指针
//父类指针转成子类指针
Animal * animal = NULL;
Cat *cat = static_cast<Cat*>(animal);
//Cat *cat1 = NULL;
//Animal *a = static_cast<Animal*>(cat1);
//引用
Animal ani;
Animal &anii = ani;//父类引用指向父类对象
Cat &cat9 = static_cast<Cat &>(anii);
Cat cat11;
Cat& cat2 = cat11;
Animal &ani2 = static_cast<Animal&>(cat2);
//static_cast用于内置的数据类型,具有继承关系的指针或者引用
}
//dynamic_cast 转换具有继承关系的指针或引用,在转换前会进行对象类型检查
void test02()
{
//基础数据类型
//int a = 10;
//char c = dynamic_cast<char>(a);
//非继承关系的指针或者引用
//Animal * ani3 = NULL;
//Building * building = dynamic_cast<Building*>(ani3);
//具有继承关系的指针
/*Animal *ani4 = NULL;不安全
Cat *c = dynamic_cast<Cat*>(ani4);*/
//出错时因为dynamic_cast会进行安全检查,大箱子(子类)可以转换成小箱子(父类),小箱子不能转换成大箱子
//子类指针转换成父类指针,大转换成小,安全
//父类指针转换成子类指针,小转换成大,不安全
Cat *cat4 = NULL;
Animal *ani5 = dynamic_cast<Animal*>(cat4);//子转父
}
//const_cast 指针,引用,对象指针
void test03()
{
//基础数据类型
int a = 1;
const int&b = a;
//b = 30;
//cout << "b=" << b << endl;
int &c=const_cast<int&>(b);//取消掉const
c = 2;
cout << "a= " << a << " b=" << b << " c=" << c << endl;
//看指针
const int *p = NULL;//取消掉const,不是取消掉本身的 ,而是由新的接收
int *p1=const_cast<int*>(p);
int *p3 = NULL;//增加const
const int *p4 = const_cast<const int*>(p3);
}
//reinterpret_cast 强制类型转换,任类型值都可以转换成其他类型值,包括函数指针
typedef void(*FUNC1)(int, int);
typedef int(*FUNC2)(int, char*);
void test04()
{
//1.无关的类型指针都可以进行转换
Building *build = NULL;
Animal *s = reinterpret_cast<Animal*>(build);
//2.函数指针转换
FUNC1 func1;
FUNC2 func2 = reinterpret_cast<FUNC2>(func1);
}
int main()
{
test03();
return 0;
}