【技术类】c++类型转换

cpp提供了四种类型转换

/*
	static_cast	
*/
class Base
{
public:
	Base():b(1){}
	int b;
};

class Dev : public Base
{
public:
	Dev():d(3){}
	int d;
};

int main()
{
	/*
		static_cast		编译时期检查
		1.普通类型转换(不能转掉volitale,const等属性)
	*/
	const int a = 10;
	float f1 = (float)a;
	float f = static_cast<float>(a);

	cout << "a: " << a << endl;
	cout << "f1:" << f1 << endl;
	cout << "f:" << f << endl;

	/*
		2.把空指针转换成目标类型的空指针
	*/
	void *p = NULL;
	int *ps = static_cast<int*>(p);
	
	/*
		3.把任何类型的表达式类型转换成void类型
	*/
	int *r = NULL;
	void *rp = static_cast<void*>(r);

	/*
		4.类层次结构中基类和派生类之间的指针,引用转换。
	*/
	Dev	 *dp = static_cast<Dev*>(new Base());	
	printf("%x\n", dp->d);		//结果是未知的
	/*
		此时dp是指向一个Base的对象,Base对象没有d
		但是dp是一个Dev类型的,那么就会访问b向下一个
		指针字节的fdfdfdfd哨兵位。
		
		奇怪的是访问了哨兵位竟然没有报错。
	*/
	return 0;
}
/*
	dynamic_cast	
	1.运行时处理,进行动态检查
	2.不能用于基本类型的转换
	3.成功的返回指向类的指针或引用,失败返回NULL
	4.使用时,基类中必须含有虚函数,否则编译不通过
	5.下行转换会有类型检查,更安全

*/
class Base
{
public:
	virtual void fun(){ cout << "Base::fun" << endl; }
};
class Dev:public Base
{
public:
	int v;
	void fun(){	cout << "Dev::fun"<<endl; }
};

int main()
{
	int a = 10;
	/*
		1.	int b = dynamic_cast<int>(a);	编译错误
			提示:1.必须是完整类类型
				  2.还要是指针或引用
	*/

	Base *bp = new Base();
	Dev *dp = dynamic_cast<Dev*>(bp);
	if (!dp)
	{
		cout << "dp is NULL" << endl;
	}

	/*
		dp->v = 10;
		2.上行转换是不安全的,调试发现dp是NULL的。
		  但是运行时上面这句没报错,只是啥都没发生
		  这点上编译器不知道为什么这么做。

		3.	Dev *bp = new Dev(); 
			Dev *dp = dynameic_cast<Dev*>(bp);
			Dev *dp1 = static_cast<Dev*>(bp);
		如果是这样的话,那么两者的效果是一样的,
	*/	
}
/*
	const_cast	(临时)添加/删除const性质
*/

int main()
{
	const int constant = 1;
	const int* constp = &constant;

	int *modifier = const_cast<int*> (constp);
	*modifier = 2;
	

	cout << "constant"<<&constant<<" "<<constant << endl;	
	cout << "constp: " << constp <<" "<< *constp << endl;	
	cout << "modifier: " << modifier <<" "<< *modifier << endl;

	/*
		constant:  0098F79C  1
		constp:    0098F79C  2
		modifier : 0098F79C  2
		1.未定义行为,目的是当一个指针或引用被const修饰时,
		  而又想修改那块内存,使用const_cast来去除指针或
		  引用的const性质来达到可以修高内存的目的,并不是
		  常量的const性质。

		  由编译器来决定结果,不可确定。
	*/

	int auto_int = 1;
	const int* autop = &auto_int;
	
	int *moden = const_cast<int*>(autop);
	*moden = 2;

	cout << &auto_int << " "<< auto_int << endl;
	cout << autop << " " << *autop << endl;
	cout << moden << " " << *moden << endl;
	
	/*
		2.迫于无奈,只有const int*了,但我们已知
		auto_int是非const的。那么就可以这样使用了。
		这是种常用方式。
	*/
	return 0;
}
/*
	reinterpret_cast
	将数据从一种类型的转换为另一种类型。所谓“通常为操作数的位模式提供较低层的重新解释”
	也就是说将数据以二进制存在形式的重新解释。
*/

int main()
{
	int i = 1;
	int s = 2;
	int *ptr = &s;

	i = reinterpret_cast<int>(ptr);
	ptr = reinterpret_cast<int*>(i);

	printf("%x\n", i);
	printf("%x\n", ptr);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值