C++中的四种强制类型转换符详解

C++ 既支持 C 风格的类型转换,又有自己风格的类型转换。C 风格的转换格式很简单,但是有不少缺点:

  • 转换太过随意,可以在任意类型之间转换。你可以把一个指向 const 对象的指针转换成指向非 const 对象的指针,把一个指向基类对象的指针转换成一个派生类对象的指针,这些转换之间的差距是非常巨大的,但是传统的C语言风格的类型转换没有区分这些。
  • C 风格的转换没有统一的关键字和标示符。对于大型系统,做代码排查时容易遗漏和忽略。

C++ 风格完美的解决了上面两个问题。

  1. 对类型转换做了细分,提供了四种不同类型转换,以支持不同需求的转换;
  2. 类型转换有了统一的标示符,利于代码排查和检视。

下面分别来介绍这四种转换:static_cast、dynamic_cast、const_cast、reinterpert_cast,它们都是类模板。

格式均为:xx_cast<type-id>(expression) ,其中type-id-要转换成什么类型,expression-被转换类型的目标变量


一、static_case(静态转换)

(1)使用场景

  • 在基本数据类型之间转换,如把 int 转换为 char,这种带来安全性问题由程序员来保证;
  • 在有类型指针与 void * 之间转换;
  • 用于类层次结构中基类和派生类之间指针或引用的转换。
    • 上行转换(派生类---->基类)是安全的;
    • 下行转换(基类---->派生类)由于没有动态类型检查,所以是不安全的。

(2)使用特点

  • 主要执行非多态的转换操作,用于代替C中通常的转换操作。
  • 隐式转换都建议使用 static_cast 进行标明和替换。
  • 不能使用 static_cast 在有类型指针内转换。

(3)示例程序如下所示:

#include <iostream>

using namespace std;

class CBase // 基类(父类)
{
    
};

class CDerived : public CBase  // 派生类(子类)
{

};

int main()
{
	// 1. 使用static_cast在基本数据类型之间转换
	float fval = 10.12;
	int ival = static_cast<int>(fval);  // float --> int
	cout << ival << endl;  // out: 10

	// 2. 使用static_cast在有类型指针与void *之间转换
	int *intp = &ival;
	void *voidp = static_cast<void *>(intp); // int* --> void*
	// cout << *voidp << endl; // error,voidp的大小未知
	long *longp = static_cast<long *>(voidp);
	cout << *longp << endl; // out: 10

	// 3. 用于类层次结构中基类和派生类之间指针或引用的转换
	// 上行转换(派生类---->基类)是安全的
	CDerived *tCDerived1 = nullptr;
	CBase *tCBase1 = static_cast<CBase*>(tCDerived1);
	// 下行转换(基类---- > 派生类)由于没有动态类型检查,所以是不安全的
	CBase *tCBase2 = nullptr;
	CDerived *tCDerived2 = static_cast<CDerived*>(tCBase2); //不会报错,但是不安全

	// 不能使用static_cast在有类型指针内转换
	float *floatp = &fval;  //10.12的addr
	//int *intp1 = static_cast<int *>(floatp); // error,不能使用static_cast在有类型指针内转换
	cout << *floatp << endl;    // out: 10.12
}

/*
输出结果:

10
10
10.12
*/

二、dynamic_cast(动态转换)

(1)使用场景

  • 用于将一个父类的指针/引用转化为子类的指针/引用(下行转换)。

(2)使用特点

  • 基类必须要有虚函数,因为 dynamic_cast 是运行时类型检查,需要运行时类型信息,而这个信息是存储在类的虚函数表中。
  • 对于下行转换,dynamic_cast 是安全的(当类型不一致时,转换过来的是空指针),而 static_cast 是不安全的。
  • 对指针进行 dynamic_cast,失败返回 NULL,成功返回正常 cast 后的对象指针;对引用进行 dynamic_cast,失败抛出一个异常,成功返回正常 cast 后的对象引用。

(3)示例程序如下所示:

#include <iostream>

using namespace std;

class CBase    // 基类(父类)
{
public:
	// dynamic_cast在将父类cast到子类时,父类必须要有虚函数
	virtual int test() { return 0; } // 一定要是 virtual
};

class CDerived : public CBase  // 派生类(子类)
{
public:
	int test() { return 1; }
};

int main()
{
	CBase *p_CBase = new CBase;  // 基类对象指针
	CDerived *p_CDerived = dynamic_cast<CDerived *>(p_CBase);  // 将基类对象指针类型转换为派生类对象指针

	CBase i_CBase;    // 创建基类对象
	CBase &r_CBase = i_CBase;    // 基类对象的引用
	CDerived &r_CDerived = dynamic_cast<CDerived &>(r_CBase);  // 将基类对象的引用转换派生类对象的引用
}

三、const_cast(常量转换)

(1)使用场景

  • 常量指针(或引用)与非常量指针(或引用)之间的转换。

(2)使用特点

  • cosnt_cast 是四种类型转换符中唯一可以对常量进行操作的转换符。
  • 去除常量性是一个危险的动作,尽量避免使用。

(3)示例程序如下所示:

#include <iostream>

using namespace std;

int main()
{
	int value = 100;
	const int *cpi = &value; // 定义一个常量指针
	//*cpi = 200;   // 不能通过常量指针修改值

	// 1. 将常量指针转换为非常量指针,然后可以修改常量指针指向变量的值
	int *pi = const_cast<int *>(cpi);
	*pi = 200;

	// 2. 将非常量指针转换为常量指针
	const int *cpi2 = const_cast<const int *>(pi); // *cpi2 = 300;  //已经是常量指针

	const int value1 = 500;
	const int &c_value1 = value1; // 定义一个常量引用

	// 3. 将常量引用转换为非常量引用
	int &r_value1 = const_cast<int &>(c_value1);

	// 4. 将非常量引用转换为常量引用
	const int &c_value2 = const_cast<const int &>(r_value1);
}

四、reinterpret_cast(不相关类型的转换)

reinterpret 的英文含义有重新转换的含义,就相当于 C 语言中不相关类型的转换,强转。


(1)使用场景

  • 用在任意指针(或引用)类型之间的转换。
  • 能够将整型转换为指针,也可以把指针转换为整型或数组。

(2)使用特点

  • reinterpret_cast 是从底层对数据进行重新解释,依赖具体的平台,可移植性差。
  • 不到万不得已,不用使用这个转换符,高危操作。

(3)示例程序如下所示:

#include <iostream>

using namespace std;

int main()
{
	int value = 100;
	// 1. 用在任意指针(或引用)类型之间的转换
	double *pd = reinterpret_cast<double *>(&value);
	cout << "*pd = " << *pd << endl;

	// 2. reinterpret_cast能够将指针值转化为整形值
	int *pv = &value;
	int pvaddr = reinterpret_cast<int>(pv);
	cout << "pvaddr = " << hex << pvaddr << endl;
	cout << "pv = " << pv << endl;
}

/*
输出结果:

*pd = -9.25596e+61
pvaddr = 8ffe60
pv = 008FFE60
*/

五、扩展

下面程序中,参数 pb 指向的是 B 类对象,pd1 的值不为0,而 pd2 的值为 0。

#include <iostream>

using namespace std;

class B
{
    int m_iNum;
    virtual void foo() {};
};
class D:public B
{
    char *m_szName[100];
};

void func(B* pb)
{
    D *pd1 = static_cast<D *>(pb);
    D *pd2 = dynamic_cast<D *>(pb);
    
	cout << pd1 << endl; //00CFF7C0
	cout << pd2 << endl; //00000000    
}

int main()
{
	B pb; //父类对象pb
	cout << "&pb: " << &pb << endl; //&pb: 00CFF7C0    
	func(&pb);

	return 0;
}

/*
输出结果:

&pb: 00CFF7C0
00CFF7C0
00000000
*/

posted @ 2019-02-16 15:07  fengMisaka  阅读(5695)  评论(0编辑  收藏  举报