C++ 補充 & C++ 11 - C++ reinterpret_cast用法詳解

reinterpret_cast用法詳解

重新解釋類型(掛羊頭,賣狗肉) 不同類型間的互轉,數值與指針間的互轉

用法: TYPE b = reinterpret_cast ( a )
TYPE必須是一個指針、引用、算術類型、函數指針.

忠告:濫用 reinterpret_cast 運算符可能很容易帶來風險。 除非所需轉換本身是低級別的,否則應使用其他強制轉換運算符之一。

demo 代碼(一)

#include <iostream>

using namespace std;

class Animal
{
public:
	void cry()
	{
		cout << "動物叫" << endl;
	}
};

class Cat :public Animal
{
public:
	void cry()
	{
		cout << "喵喵" << endl;
	}
};

class Dog :public Animal
{
	void cry()
	{
		cout << "旺旺" << endl;
	}
};

int main(void)
{
	/* 用法一 數值與指針之間的轉換 */
	int* p = reinterpret_cast<int*>(0x999999);
	int val = reinterpret_cast<int>(p);

	/* 用法二 不同類型指針和引用之間的轉換 */
	Dog dog1;
	Animal* a1 = &dog1;
	a1->cry();

	Dog* dog1_p = reinterpret_cast<Dog*>(a1);
	Dog* dog2_p = static_cast<Dog*>(a1); /* 如果能用 static_cast, static_cast 優先 */

	//Cat* cat1_p = static_cast<Cat*>(a1);
	//Cat* cat2_p = static_cast<Cat*>(dog1_p); /* NO! 不同類型指針轉換不能使用static_cast */
	Cat* cat2_p = reinterpret_cast<Cat*>(dog1_p);

	Animal a2 = dog1;
	Dog& dog3 = reinterpret_cast<Dog&>(a2); /* 引用強轉用法 */

	dog1_p->cry();
	dog2_p->cry();

	cat2_p->cry();

	system("pause");
	return 0;
}

編譯:

在這裏插入圖片描述

結語:

時間: 2020-07-02

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章