一、static_cast
1、用于类层次结构之间基类和派生类指针和引用之间的转换,进行向上转型是安全的,但是进行向下转型是不安全的,但是是可以转换的
向上转型:我们知道基类的引用和指针都可以指向派生类的对象,那么将派生类的指针或者引用强转为基类的指针或者引用,那么这就是向上转型,也就是向父类转
向下转型:向下转型就和向上转型相反,它是将父类的指针或者引用,强制转换为子类的指针或者引用
class Base
{
public:
void fun1()
{
cout << "Base" << endl;
}
};
class Derive :public Base
{
public:
void fun2()
{
cout << "Derive" << endl;
}
};
int main(void)
{
Base* m_pbase = NULL;
Derive* m_pderive = NULL;
//向上转型
m_pbase = static_cast<Base*>(m_pderive);
//既然都转换成了基类指针,那么调用基类函数
m_pbase->fun1();
m_pderive->fun1();
//向下转型
m_pderive = static_cast<Derive*>(m_pbase);
//既然都转换成了派生类指针,那么调用派生类函数
//m_pbase->fun2(); //这个时候编译就错误了,所以是不安全的
m_pderive->fun2();
return 0;
}
2、用于基本数据类型之间的转换
int main(void)
{
char c = 'A';
int a = 2;
double b = 3.14;
float f = 5.26f;
cout << typeid(c).name() << endl;
cout << typeid(a).name() << endl;
cout << typeid(b).name() << endl;
cout << typeid(f).name() << endl;
//double --> int
a = static_cast<int>(b);
cout << a << endl;
return 0;
}
3、把空类型指针转换为目标类型的空指针
int main(void)
{
void* p = NULL;
int a = 3;
int* pi = &a;
if (pi == NULL)
{
cout << "p == NULL" << endl;;
}
pi = static_cast<int*>(p);
if (pi == NULL)
{
cout << "p == NULL";
}
return 0;
}
4、把任何类型的表达式转换为void类型
二、const_cast:解除常量属性,使其可以修改
int main(void)
{
const int a = 3;
const int* p = &a;
cout << *p << endl;
//a = 4; //编译出错
//*p = 5; //编译出错
int* p1 = const_cast<int*>(p);
*p1 = 5;
cout << *p << endl;
return 0;
}
三、reinterpret_cast:可以将一个类型的指针转换为其它任意类型的指针,也可以用在指针和整形数据之间的转换
它是很危险的,如果我们没有使用它的充分理由,那么就不要使用它
class A
{
public:
void fun()
{
cout << "haha" << endl;
}
};
int main(void)
{
int a = 3;
A* aa = new A();
char* p = reinterpret_cast<char*>(a);
int* pi = reinterpret_cast<int*>(aa);
//pi->fun(); 错误
//cout << a << endl;
//cout << (int)*p << endl;//直接崩溃
}
四、dynamic_cast:
1、其它三种都是编译时期完成的,但是dynamic_cast是运行时期处理的,运行时期要进行类型检查
2、不能用于内置类型之间的基础转换
3、如果转换成功,返回的是指向目标类型的指针或者引用,如果失败返回NULL
4、使用dynamic_cast转换的时候基类一定要有虚函数,否则编译不通过
5、它可以向上转型,和向下转型,而且向下转型是安全的
class Base
{
public:
virtual void fun()
{
cout << "Base" << endl;
}
};
class Derive :public Base
{
public:
virtual void fun()
{
cout << "Derive" << endl;
}
};
int main(void)
{
//都是安全的
Base* base = new Base();
Derive* derive = new Derive();
base = reinterpret_cast<Base*>(derive);
base->fun();
derive->fun();
derive = reinterpret_cast<Derive*>(base);
base->fun();
derive->fun();
return 0;
}