类型转化是将一种数据类型转换成另外一种数据类型;
类型转换
静态转换
父子转换
用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换。
- 进行上行转换(把派生类的指针或引用转换成基类表示)是安全的;
- 进行下行转换(把基类指针或引用转换成派生类表示)时,由于没有动态类型检查,所以是不安全的。
// demo01_类型转换.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//静态类型转换
void test()
{
char c = 'a';
double d = static_cast<double>(c);
cout << d << endl;
}
//父子静态转换
class Base
{
public:
private:
};
class Child : public Base{
};
class Other{
};
void test01()
{
Base *base = NULL;
Child *child = NULL;
//把base转换为child*类型
Child *child2 = static_cast<Child *>(base);
//把child转换为base*类型
Base *base1 = static_cast<Base *>(child);
//Other转换
//Other *other = static_cast<Other *>(base); //必须需要父子关系才可以转换
}
int _tmain(int argc, _TCHAR* argv[])
{
test();
test01();
system("pause");
return 0;
}
没有父子关系的自定义类型不可以转换
继承引用转换
class Animal{
};
class Dog : public Animal{
};
void test02(){
//继承关系指针转换
Animal* animal01 = NULL;
Dog* dog01 = NULL;
//子类指针转成父类指针,安全
Animal* animal02 = static_cast<Animal*>(dog01);
//父类指针转成子类指针,不安全
Dog* dog02 = static_cast<Dog*>(animal01);
}
void test03(){
Animal ani_ref;
Dog dog_ref;
//继承关系指针转换
Animal& animal01 = ani_ref;
Dog& dog01 = dog_ref;
//子类指针转成父类指针,安全
Animal& animal02 = static_cast<Animal&>(dog01);
//父类指针转成子类指针,不安全
Dog& dog02 = static_cast<Dog&>(animal01);
}
//无继承关系指针转换
void test04(){
Animal* animal01 = NULL;
Other* other01 = NULL;
//转换失败
//Animal* animal02 = static_cast<Animal*>(other01);
}
动态转换
dynamic_cast主要用于类层次间的上行转换和下行转换;
在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;
在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全;
#include "stdafx.h"
#include <iostream>
using namespace std;
void test()
{
//基础数据类型不可以转换
/*
char c = 'a';
double d = dynamic_cast<double>(c);
*/
}
class Base{
virtual void func()
{
;
}
};
class Child : public Base{
virtual void func()
{
;
}
};
class Other{
};
void test01()
{
Base* base = NULL;
Child* child = NULL;
//child转base
Base* base1 = dynamic_cast<Base *>(child);
//base转child 不安全类型转换
//Child* child1 = dynamic_cast<Child *>(base);
//如果发生了多态,那么可以让基类转换为派生类
//多态情况
Base* base2 = new Child;
Child* child2 = dynamic_cast<Child *>(base2);
}
int _tmain(int argc, _TCHAR* argv[])
{
test01();
return 0;
}
常量转换
不能直接对非指针和非引用的变量使用const_cast操作符去直接移除它的const.
常量指针被转化成非常量指针,并且仍然指向原来的对象;
常量引用被转换成非常量引用,并且仍然指向原来的对象;
#include <iostream>
using namespace std;
void test()
{
const int* p = NULL;
//祛除const
int* newp = const_cast<int *>(p);
//
int* p1 = NULL;
const int* newp1 = const_cast<int *>(p1);
//不能对非指针或非引用的变量进行转换
const int p2 = 10;
//int b = const_cast<int>(p2); //错误类型转换
//引用
int num = 10;
int &numref = num;
const int& numRef = static_cast<const int &>(numref); //引用就可以进行类型转换
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}