您的位置:首页 > 编程语言 > C语言/C++

C++ 关于static_cast reinterpret_cast dynamic_cast 以及 const_cast 用于类型转换的函数使用 20180315 day7

2018-03-15 10:35 711 查看
先观察一个例子#include<iostream>

using namespace std;

// dynamic_cast 实现父类与子类之间的类型转换 动态类型转换 向下转型
class Animal //父类
{
public:
virtual void cry()=0; //虚函数

private:

};

class dog :public Animal //类的继承
{
public:
void cry()
{
cout << "dog" << endl;
}

void doHome()
{
cout << "看家" << endl;
}

};

class cat :public Animal //类的继承
{
public:
void cry()
{
cout << "cat" << endl;
}

void doHome()
{
cout << "吸吸" << endl;
}

};

void play(Animal * base) //该函数 1 有继承 , 2 虚函数重写 3 父类指针 指向子类 =====>实现了多态
{
base->cry();
//dynamic_cast 运行时类型的识别
dog * a = dynamic_cast<dog *>(base); //dynamic_cast 实现父类向子类的转换 向下转型

if (a != NULL)
{
a->doHome();
}

cat * a1 = dynamic_cast<cat *>(base);

if (a1 != NULL)
{
a1->doHome();
}

}

void makeTrue(const char * p)
{
//p[0] = 'z'; 如果直接调用就会报错,因为 const修饰的是常量类型,不允许值得修改
char *pr = NULL;

pr = const_cast<char *>(p); //将const char *转为 char *

pr[0] = 'z';
cout << p << endl;

}

void main()
{

double pi = 3.14159;
int num = (int)pi; //c方式的类型转换
int num_1 = static_cast<int>(pi); //静态类型转换 编译的时候C++编译器会做类型检查
int num_2 = pi; //隐式类型转换 但是编译器会出现warning 因此c语言中隐式类型均可以使用static_cast进行类型转换

//static_cast 不可以进行指针之间的类型转换

//
char *p1 = "hello cjlu";
int * p2 = NULL;

p2 = reinterpret_cast<int *>(p1); //类似于强制类型转换
int * num_3 = reinterpret_cast<int*>(num);

//总结 通过 static_cast<>() 与 reinterpret_cast<>() 将c语言的强制类型转换全部覆盖

//验证dynamic_cast
dog ddd;
cat ccc;
play(&ddd);
play(&ccc);

//关于const_cast 的来说,一般可以理解为是对去除常量的属性

char ppp[] = "hello cjlu";

//但是需要确保 ppp所指向的内存空间可以修改,否则会出现中断

char * p = "123"; //例如这里就是p因为没有分配内存空间,为常量,带入函数也是不可以修改

makeTrue(ppp);

system("pause");

}
// dynamic_cast  实现父类与子类之间的类型转换   动态类型转换  向下转型
//关于const_cast 的来说,一般可以理解为是对去除常量的属性
int num_1 = static_cast<int>(pi);   //静态类型转换 编译的时候C++编译器会做类型检查
p2 = reinterpret_cast<int *>(p1);   //类似于强制类型转换
static_cast<>() //不可以将char *转为 int *reinterpret_cast<>() //不可以转换 int 到 char 一般只用于指针类型之间的转换
两者不可以混用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐