C++中四种类型转换方式

    (1) static_cast

     (2) const_cast

     (3) dynamic_cast

     (4) reinterpret_cast


实例:

// 20145_25_3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

//const int *fun(int x,int y)
//{
//}
class Base
{
public:
	virtual void m() 
	{ cout << "This is Base" << endl;};
};
class Derived: public Base
{
public:
	void m()
	{cout << "This is Derived" << endl;}
	void fun()
	{ cout << "This is a Derived fun" <<endl;}
};

int _tmain(int argc, _TCHAR* argv[])
{
	//static_cast  最常用的类型转换符
	float f = 66.5;
	char c =static_cast<char>(f);
	cout << c << endl;

	cout <<"********************"<<endl;
   //const_cast 用于去出const属性,把const类型的指针变为非const类型的指针
	const int a = 100;
	const int *p = &a;
	int *m = const_cast<int *>(p);
	*m = 50;
	cout << "a = " << a << endl;
	cout << "*p= " << *p << endl;
	cout << "*m= " << *m << endl;

	cout << "******************"<<endl;
	//dynamic_cast  该操作符用于运行时检查该转换是否类型安全,但只在多态类型时合法,即该类至少具有一个虚拟方法。
	Base *pBase;
	Derived derived;
	pBase = &derived;
	pBase->m();
	if(Derived *pDerived = dynamic_cast<Derived *> (pBase))
		pDerived->fun();

	//reinterpret_castinterpret是解释的意思,reinterpret即为重新解释,此标识符的意思即为数据的二进制形式重新解释,但是不改变其值。
	int i;
	char *ptr = "hello world!";
	i = reinterpret_cast<int>(ptr);

	cout << "i = " << endl;

	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值