C++类型转换

C++类型转换

C++和C语言中类型转换是有区别的,在C语言中一般只管类型转换不用对其进行安全检查。但是在C++中我们不仅要对其进行类型转换,系统还会对其进行安全检查,因此我们在C++中常用到以下四个类型转换的关键字:
1–static_cast 一般类型转换
2–dynamic_cast 通常在基类和派生类之间转换时使用
3–const_cast 主要针对const的转换
4–reinterpret_cast 用于进行没有任何关联之间的转换,比如一个字符指针转换为一个整型数。

#include
using namespace std;

//static_cast 一般类型转换
//dynamic_cast 通常在基类和派生类之间转换时使用
//const_cast 主要针对const的转换
//reinterpret_cast 用于进行没有任何关联之间的转换,比如一个字符指针转换为一个整型数。

class Building {

};
class Animal {

};
class Cat :public Animal {

};

/*****************************///
//1-static_cast 一般类型转换
void test01() {
int a = 97;
char c = static_cast(a);
cout << c << endl;

//基础数据类型指针
//int* p = NULL;
//char* cp = static_cast<char*>(p);//基础数据指针类型不能转。

// 对象指针
//Building* building = NULL;
//Animal* ani = static_cast<Animal*>(building);//对象指针类型不能转。

//转换具有继承关系的对象指针
//父类指针可以转换成之类指针
Animal* ani = NULL;
Cat* cat = static_cast<Cat*>(ani);
//子类指针转换成父类指针
Cat* soncat = NULL;
Animal* anifather = static_cast<Animal*>(soncat);

Animal aniobj;
Animal& aniref = aniobj;
Cat& cat1 = static_cast<Cat&>(aniref);

Cat catobj;
Cat& catref = catobj;
Animal& anifather2 = static_cast<Animal&>(catref);

//static_cast  用于内置的数据类型,还具有继承关系的指针或者引用。

}
************************/
//2-dynamic_cast 转换具有继承关系的指针或者引用,在转换前会进行对象类型检查
void test02() {
//基础数据类型
//int a = 10;
//char c = dynamic_cast(a);//基础数据类型不能转换。

//非继承关系指针
//Animal* ani = NULL;
//Building* building = dynamic_cast<Building*>(ani);//非继承关系指针不能转换

//具有继承关系指针
//Animal* ani = NULL;
//Cat* cat = dynamic_cast<Cat*>(ani);//这是父类指针转换成子类指针,不安全。系统不让转。
//原因在于dynamic做类型安全检查。

Cat* cat2 = NULL;
Animal* ani = dynamic_cast<Animal*>(cat2);//这是子类指针转换成父类指针,安全。

//结论:dynamic只能转换具有继承关系的指针或者引用,并且只能由子类类型转成基类型。

}
///********************************/
//3-const_cast 针对指针、引用、对象指针的const属性的去掉。
void test03() {
//1-基础数据类型
int a = 10;
const int& b = a;
//b = 10;//此时b是不能被修改的。
int& c = const_cast<int&>(b);
c = 20;
cout << “a:” << a << endl;
cout << “b:” << a << endl;
cout << “c:” << a << endl;

//看指针
const int* p = NULL;
int *p2=const_cast <int*>(p);

int* p3 = NULL;
const int* p4 = const_cast<const int*>(p3);

//const_cast 增加或者去除变量const性。

}
/*****************************************/
//4-reinterpret_cast 强制类型转换(任何类型)

typedef void(FUNC)(int, int);
typedef int(FUNC2)(int, char);
void test04() {
//(1)无关的指针类型都可以进行转换。
Building
building = NULL;
Animal* ani = reinterpret_cast<Animal*>(building);

//(2)函数指针转换
FUNC func1;
FUNC2 = reinterpret_cast<FUNC2>(func1);

}

int main() {
test01();
test03();
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值