C++回顾(十七)—— 类型转换

17.1 static_cast(expr)

  • static_cast强制类型转换
    用于基本类型间的转换,但不能用于基本类型指针之间的转换
    用于有继承关系类对象之间的转换和类指针之间的转换

  • static_cast是在编译期间转换的,无法在运行时检测类型
    所以类类型之间的转换有可能存在风险

在这里插入图片描述
在这里插入图片描述
完整示例代码:

#include <iostream>

using namespace std;

class Parent
{
};

class Child : public Parent
{
};

int main()
{
	int a = 1;
	char ch = 'x';

	a = static_cast<int>(ch);   //用于普通类型之间的转换

	//int *p = static_cast<int *>(&ch);  //不能用于普通类型指针之间的转换

	Parent p;
	Child c;

	p = static_cast<Parent>(c);   //用于有继承关系的类对象之间的转换
	Parent *p1 = static_cast<Parent *>(&c);    //用于类对象指针之间的转换   
	
	return 0;
}

17.2 reinterpret_cast(expr)

  • reinterpret_cast强制类型转换
    用于指针类型间的强制转换
    用于整数和指针类型间的强制转换
  • reinterpret_cast直接从二进制位进行复制,是一种极其不安全的转换

在这里插入图片描述
在这里插入图片描述
示例代码:

#include <iostream>

using namespace std;

int main()
{
	int b = 10;
	int a = 100;
	char *p = reinterpret_cast<char *>(&a);   //用于普通类型指针之间的转换(不安全)
	cout << *(p + 1) << endl;
	cout << *(&a + 1) << endl;

	int *q = reinterpret_cast<int *>(100);    //用于数字和指针之间的转换(很容易出现野指针)
	*q = 1;

	return 0;
}

17.3 const_cast(expr)

const_cast用于去除变量的const属性
在这里插入图片描述
示例代码:

#include <iostream>

using namespace std;

int main()
{
	const int a = 1;     //常量(在编译时就对a进行了替换,这里和C语言不同)
	// int *p = (int *)&a;
	int *p = const_cast<int *>(&a);
	*p = 100;
	cout << "a = " << a << endl; // a = 1;
	cout << "*p = " << *p << endl; // *p = 100;

	const int &m = 1;       
	int &n = const_cast<int &>(m);
	n = 100;
	cout << " m = " << m << endl; // m = 100;
	cout << " n = " << n << endl; // n = 100;

	const int x = 1;
	int &y = const_cast<int &>(x);
	y = 100;
	cout << "x = " << x << endl; // x = 1;;
	cout << "y = " << y << endl; // y = 100;

	return 0;
}

运行结果:
在这里插入图片描述
在C语言中:

#include <stdio.h>

int main() {
    const int a = 1;
    int *p = &a;
    *p = 100;

    printf("a = %d\n", a); // a = 100;
    printf("*p = %d\n", *p); // *p = 100;

    return 0;
}

在这里插入图片描述

17.4 dynamic_cast(expr)

dynamic_cast强制类型转换
主要用于类层次间的转换,还可用于类之间的交叉转换
dynamic_cast具有类型检查功能,比static_cast更安全

在这里插入图片描述
示例代码:

#include <iostream>

using namespace std;

class Parent
{
public:
	virtual void f()
	{
	}
};

class Child : public Parent
{
public:
	void f()
	{
	}
};

int main()
{
	Child *c = new Child;
	delete c;

	//c = static_cast<Child *>(new Parent);  //派生类指针指向基类对象(错误,但是编译器检查不出来)

	c = dynamic_cast<Child *>(new Parent);   //运行的时候做类型检查,如果不能转换,则返回NULL,比static_cast安全
	if (NULL == c)
	{
		cout << "强转失败" << endl;
	}
	else
	{
		cout << "强转成功" << endl;
		delete c;
	}

	return 0;
}

运行结果:
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值