类型转换:(static_cast,dynamic_cast,const_cast,reinterpret_cast)

#include<iostream>

using namespace std;

class Buliding {};

class Person {};

class Student :public Person {};

//函数指针

typedef void (*FUNC)(int, int);

typedef void(*FUNC1)(int, char*);

void test01()

{

//reinterpret_cast强制类型转换,无关类型转换,函数指针转换都可以。

//可以转换无关类指针

/*Buliding *bul = NULL;

Person* per = reinterpret_cast<Person*>(bul);*/

FUNC func;

FUNC1 func1 = reinterpret_cast<FUNC1>(func);

}

int main()

{

//可以int转为char

/*int a ;

cin >> a;

char c = static_cast<char>(a);

cout << c << "\n";*/

//不可以string转为int和char

/*string s;

cin >> s;

int a = static_cast<int>(s);

char c = static_cast<char>(s);*/

//char可以转为int不能转为string

/*char a = 'l';

int b = static_cast<int>(a);

string s = static_cast<string>(a);*/

//无法转换无关类指针

/*Buliding *bul = NULL;

Person* per = static_cast<Person*>(bul);*/

//可以从父类指针到子类指针的转换

/*Person* per = NULL;

Student* stu = static_cast<Student*>(per);*/

//可以子类指针到父类的转换

/*Student* stu = NULL;

Person* per = static_cast<Person*>(stu);*/

//可以从父类引用到子类引用的转换

/*Person per;

Person& p1 = per;

Student& stu = static_cast<Student&>(p1);*/

//可以子类引用到父类引用的转换

/*Student stu;

Student& s1 = stu;

Person per = static_cast<Person&>(s1);*/

//dynamic_cast

//

//无法基本类型转换

/*int a = 23;

char c = dynamic_cast<char>(a);*/

//无法转换无关类指针

/*Buliding* bul = NULL;

Person* per = dynamic_cast<Person*>(bul);*/

//无法从父类指针到子类指针的转换

/*Person* per = NULL;

Student* stu = dynamic_cast<Student*>(per);*/

//可以子类指针到父类的转换

/*Student* stu = NULL;

Person* per = dynamic_cast<Person*>(stu);*/

//不可以从父类引用到子类引用的转换

/*Person per;

Person& p1 = per;

Student& stu = dynamic_cast<Student&>(p1);*/

//可以子类引用到父类引用的转换

/*Student stu;

Student& s1 = stu;

Person per = dynamic_cast<Person&>(s1);*/

//const_cast是为了去除或增加变更量的const性;

//const int a = 10;

const修饰的不能修改

a = 20;

引用必须用const修饰

//const int &b = a;

b不能被修改

b = 20;

//int& c = const_cast<int&>(b);

//c = 20;

//cout << a << "\n";

//cout << b << "\n";

//cout << c << "\n";

//const int* p = NULL;

//不能有其他指针指向

//int* p1 = p;

//可以用const_cast来取消const性;

//int* p2 = const_cast<int*>(p);

//int* p3 = NULL;

//可以用const_cast来增加const性;

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

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值