#define _CRT_SECURE_NO_WARNINGS 1
#include
using namespace std;
void test01()
{
//static_cast在C++中用于将表达式的值转换为指定的类型,但没有运行时类型检查来保证转换的安全性。
//主要有以下用法:
//(1)用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换。
//(2)用于基本数据类型之间的转换,如把int转换成char,把int转换成enum。这种转换的安全性也要开发人员来保证。
//(3)把空指针转换成目标类型的空指针。
//(4)把任何类型的表达式转换成void类型。
//注意:static_cast不能转换掉expression的const、volatile、或者__unaligned属性。
//1. 基本数据类型转换
char con = 'A';
double temp = static_cast(con); //语法:stastic_cast<目标类型>(变量)
cout << temp << endl;
//2. 父类和子类之间的指针转换
class base {};
class Son : public base {};
class Dog {};
cout << "size of base = " << sizeof(base) << endl;
cout << "size of Son = " << sizeof(Son) << endl;
base* pbase = NULL;
Son* pSon = NULL;
Dog* pDog = NULL;
//父类转子类,自下向上类型,不安全,
pSon = static_cast(pbase);
//子类转父类,自上向下类型,安全
pbase = static_cast(pSon);
//无继承的类之间的转换
//pDog = static_cast(pbase); //报错,没有继承关系的类之间不存在静态转换
//3. 不能用于基本类型指针之间的转换
//int* pInt = NULL;
//double pdouble = static_cast(pInt);
}
void test02()
{
//1. 不允许内置的基本数据类型转换
//char con = 'A';
//int temp = dynamic_cast(con);
//int ret = 200;
//double size = dynamic_cast(ret);
//不允许,dynamic_cast的语法检测更为严谨,如果转换过程中会发生精度丢失,内存越界等,都会报错
//2. 父类和子类之间的指针转换
class base {};
class Son : public base {};
class Dog {};
base* pbase = NULL;
Son* pSon = NULL;
Dog* pDog = NULL;
//父转子不安全,会发生越界,报错
//pSon = dynamic_cast(pbase);
//子转父,正常运行
pbase = dynamic_cast(pSon);
//无继承之间的类转换,报错
//pDog = dynamic_cast(pbase);
//3. 发生多态:
class basec { virtual void func() {} };
class Sonc : public basec { void func() {} };
basec* pbasec = new Sonc;
//父转子,发生那个多态,安全的
Sonc* pSonc = dynamic_cast(pbasec);
}
int main()
{
test01();
test02();
return 0;
}