类型转换
类型转换(cast)是将一种数据类型转换成另一种数据类型。
静态转换 static_cast<目标类型>(转换数据)
1、可以转换基本数据类型
//静态类型转换static_cast<类型>(原始数据)
void static_change() {
int a = 10;
double b = static_cast<double>(a);
char c = 'a';
int d = static_cast<int>(c);
cout << d << endl;
//cout << b << endl;
}
2、基类和派生类型转换
如果没有继承关系的自定义类型不可以进行转换
//父子类型转换
class Base
{
public:
virtual void dowork() {};
private:
int m_age;
string name;
};
class Person :public Base
{
public:
virtual void dowork() {};
private:
int salary;
};
void test1()
{
Base A;
Person B;
cout << typeid(B).name() << endl;
//子转父可以
A = static_cast<Base>(B);
//父转子,不可以,不安去
//B = static_cast<Person>(A);
cout << "转换后:"<<typeid(static_cast<Base>(B)).name() << endl;
};
动态转换 dynamic_cast<目标类型>(转换数据)
- 不可以转换基础数据类型
- 父子之间可以进行转换
- 父转子,不可以,不安去
- 子转父,可以
- 如果发生多态,都可以进行
void test04()
{
Base2* base = NULL;
Child2* child = NULL;
//child转Base2 * 安全
Base2* base2 = dynamic_cast<Base2*>(child);
//base 转Child2 * 不安全
//Child2 * child2 = dynamic_cast<Child2*>(base);
//dynamic_cast 如果发生了多态,那么可以让基类转为派生类 ,向下转换
Base2* base3 = new Child2;
Child2* child3 = dynamic_cast<Child2*>(base3);
}
常量转换 const_cast<目标类型>(转换数据)
// 常量转换(const_cast)
void test05()
{
const int * p = NULL;
//取出const
int * newp = const_cast<int *>(p);
int * p2 = NULL;
const int * newP2 = const_cast<const int *>(p2);
//不能对非指针 或 非引用的 变量进行转换
//const int a = 10;
//int b = const_cast<int>(a);
//引用
int num = 10;
int &numRef = num;
const int &numRef2 = static_cast<const int &>(numRef);
}
重新解释转换 reinterpret_cast<目标类型>(转换数据)
//重新解释转换(reinterpret_cast)
void test06()
{
int a = 10;
int * p = reinterpret_cast<int *>(a);
Base * base = NULL;
Other * other = reinterpret_cast<Other*>(base);
//最不安全 ,不推荐
}