static_cast,const_cast,reinterpret_cast, dynamic_cast的功能与区别

前言

这四种类型转换操作符功能有所不同,对应不同的使用场景。

1.static_cast(静态转换)

主要用于执行已知类型之间的安全、合法类型转换,例如数值之间的转换或在继承层次结构中的相关类之间的转换。这种转换在编译时完成,不执行运行时的类型检查。注意,它可以将指向基类的指针(或引用)转换为指向派生类的指针(或引用),这是不安全的。
下面是一个不安全地使用static_cast的例子。

class Base {};
class Derived : public Base 
{
public:
	Derived() : name("Tom") {}
	
	void print()
	{
		std::cout << name << std::endl;
	}
private:
	std::string name
};
// Derived &der = Base();  // error
Derived &der = static_cast<Derived &>(Base());	// ok
der.print();	// undefined, may lead to runtime error
2.const_cast(常量转换)

主要用于去除指向常量对象的指针或引用的常量属性,使其能够修改其指向的对象。当需要修改数据但受制于const属性时可以使用,但一般常量对象有不能修改的理由,因此该操作需要谨慎使用。
下面是一个使用const_cast更改常量引用的例子。

// Initially, n refers to a temporary storage holding the literal "3"
const int &n = 3;
// The temporary storage now contains the value "4"
const_cast<int &>(n) = 4;
/*
 * However, this doesn't mean the literal "3" itself in memory has changed.    	
 * Literals like "3" are typically stored in read-only memory and cannot be 
 * directly modified. Instead, you've modified the temporary storage 
 * associated with the reference n.
 */

记住,const_cast只用来改变“指针或引用”的底层(low-level)常量属性,不要直接传变量的值给它,否则会导致未定义的结果。因为是传值调用,可以肯定的是不会改变原来的值。看一个例子:

// Undefined behavior
const int s = 0;
const_cast<int &>(s) = 123;
std::cout << s << std::endl;	// output: 0

尽管此代码可能会通过编译,但不会输出预期的结果。

3.reintepret_cast (重新解释转换)

顾名思义就是重新解释指针或引用所指向的对象的类型及其内存数据结构,用于执行低级别、危险的类型转换,通常用于不相关的类型之间,或需要操作二进制表示的数据时。不执行类型检查,而是将数据的二进制表示方式重新解释。通常用于将指针转换为整数或反之,或者需要在数据的二进制表示之间执行转换。
它与static_cast的区别就在于,它不需要转换前后的两种类型相关。

double d = 2.0;
double &dd = d;
int &i = reintepret_cast<int &>(dd);	// undefined behavior
int *ii = reintepret_cast<int *>(0);	// ii == NULL / nullptr
4.dynamic_cast(动态转换)

用于在多态类层次结构中执行安全的向下转型,即从基类指针或引用向派生类指针或引用的转换。它执行运行时类型检查,确保类型转换在运行时是安全的,且只能用于具有虚函数的类,通常在多态上下文中使用。如果类型转换不合法,将返回空指针或抛出异常。

class Base {};
class Derived : public Base 
{
public:
	void print()
	{
		std::cout << "Derived" << std::endl;
	}
};

Base &b = Derived();
Derived &d = dynamic_cast<Derived &>(b);
if (d)
{
	d.print();
}
else
{
	std::cout << "cann't convert to Derived *" << std::endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HilariousDog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值