36C++语言级的四种类型转换

C++语言级的四种类型转换

  • const_cast: 去掉常量属性的类型转换
  • static_cast: 提供编译器认为安全的类型转换
  • reinterpret_cast: 类似C风格的强制类型转化
  • dynamic_cast: 主要用在继承结构中,可以支持RTTI类型识别的上下转换
#include <iostream>
using namespace std;

class Base
{
public:
	virtual void func() = 0;
};

class Derive1 : public Base
{
public:
	void func() { cout << "call Derive1::func" << endl; }
};

class Derive2 : public Base
{
public:
	void func() { cout << "call Derive2::func" << endl; }
	// 实现新功能API
	void derive02func()
	{
		cout << "call Derive2::derive02func" << endl;
	}
};

void showFunc(Base* p)
{
	// dynamic_cast会检查p指针是否指向的是一个Derive2类型的对象?
	// p->vfptr->vftable RTTI信息 如果是,dynamic_cast转换类型成功,
	// 返回Derive2对象的地址给pd2;否则返回nullptr
	Derive2* pd2 = dynamic_cast<Derive2*>(p);
	if (pd2 != nullptr)
	{
		pd2->derive02func();
	}
	else
	{
		p->func();
	}
}

int main()
{
	Derive1 d1;
	Derive2 d2;
	showFunc(&d1);
	showFunc(&d2);

	return 0;
}
posted @ 2024-03-04 21:36  SIo_2  阅读(9)  评论(0)    收藏  举报