不是必要操作,就不要经常使用类型转换
静态转换(static_cast)
用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换
- 进行上行转换(把派生类的指针或引用转换成基类表示)是安全
- 进行下行转换(把基类指针或引用转换成派生类表示)时,由于没有动态类型检查,所以是不安全的
//父子之间的转换
class Base{};
class Child : public Base {};
class Other {};
void test02()
{
Base *base = NULL;
Child *child = NULL;
//向下转换 不安全
Child *child2 = static_cast<Child*>(base);
//向上转换 安全
Base *base2 = static_cast<Base*>(child);
//Other *other = static_cast<Other*>(base); //类型转换无效
}
用于基本数据类型之间的转换,如把int转换成char,把char转换成int,这种转换的安全性也要开发人员来保证。
void test01()
{
char a = 'a';
double d = static_cast<double>(a);
cout << "d = " << d << endl;
}
动态转换(dynamic_cast)
基本类型不可转换【因为动态转换非常严格,失去精度 或这不安全都不可以转换】
在进行向下转换的时候,如果发生了多态,那么可以让基类转换为派生类,是安全的
//父子之间的转换
class Base{};
class Child : public Base {};
class Other {};
void test02()
{
Base *base = NULL;
Child *child = NULL;
//向下转换 不安全
//Child *child2 = dynamic_cast<Child*>(base);
//发生多态后,可以向下转换 安全
Base *base3 = new Child;
Child *child3 = dynamic_cast<Child*>(base3);
//向上转换 安全
Base *base2 = dynamic_cast<Base*>(child);
//Other *other = dynamic_cast<Other*>(base); //类型转换无效
}
常量转换(const_cast)
不能直接对非指针或非引用的变量使用const_cast 操作符去移除它的const
void test03()
{
const int *p = NULL;
//去除const
int *np = const_cast<int*>(p);
int *p2 = NULL;
const int * np2 = const_cast<const int *>(p2);
int num = 10;
int &numRef = num;
const int &numRef2 = static_cast<const int&>(numRef);
//不能对非指针 或 非引用的 变量进行转换
//const int a = 10; //直接放符号表了
//int b = const_cast<int>(a)
}