原创 linux下c++ lesson17 强制类型转换

28 篇文章 0 订阅

1-static_cast.cpp

#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;
}

2-reinterpret_cast.cpp

#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;
}

3-const_cast.cpp

#include <iostream>

using namespace std;

int main()
{
	const int a = 1;     //常量
	int *p = const_cast<int *>(&a);
	*p = 100;
	cout << a << endl;

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

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

	return 0;
}

4-dynamic_cast.cpp

#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、付费专栏及课程。

余额充值