#include<iostream>
using namespace std;
//C++类型转换:
//1.静态类型转换:
void test01()
{
char a = 'a';
double b = static_cast<double>(a);
cout << "b=" << b << endl;
}
//父子之间的转换:
class Base{};
class Child:public Base{};
class Other{};
void test02()
{
Base * a = NULL;
Child *b = NULL;
//向下类型转换,不安全;
Child * c = static_cast<Child*>(a);
//向上类型转换,安全;
Base *d = static_cast<Base*>(b);
//转Other类型:
//Other * o = static_cast<Other*>(a);
//转换无效,必须要有父子关系才能转;
}
//static_cast使用: static_cast<要转换的类型>(原始对象);
//动态转换:
void test03()
{
char a = 'a';
//double d = dynamic_cast<double>(a);
//会报错;基础类型不可以转换;
//非常严格,失去精度或者不安全都不可以转换;
}
//父子关系:
class Base2{};
class Child2:public Base2{};
void test04()
{
Base2 * base = NULL;
Child2 * child = NULL;
//child转base,安全
Base2 * base2 = dynamic_cast<Base2*>(child);
//base转child,不安全
//Child2 *child2 = dynamic_cast<Child2*>(base);
}
//dynamic_cast如果发生了多态,那么可以让基类转换为派生类;
class Base3
{
virtual void func(){}
};
class Child3 :public Base3
{
void func() {}
};
//此时发生了多态:
void test04()
{
Base3* base = new Child3;
Child3 * child = dynamic_cast<Child3*>(base);
//多态的时候父子互相转换都可以;
}
int main()
{
test01();
system("pause");
return 0;
}