demo_type_cast_6_all_test.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 59 行

CPP
59
字号

//***********************************************************
// 使用typeid操作符支持C++运行时类型信息(RTTI)特征
// 此时必须包含typeinfo.h头文件,
// 并启用RTTI编译选项Enable Run-Time Type Information
//***********************************************************
// 综合运用:typeid,dynamic_cast,static_cast,reinterpret_cast
//***********************************************************

# include <iostream.h>
# include <typeinfo.h>

class Base
{
public:
	virtual void func() { cout<<"func() in Base"<<endl; }
};

class Derived: public Base 
{
public:
	void func() { cout<<"func() in Derived"<<endl; }
	void func_new() { cout<<"func_new() in Derived"<<endl; }
};

void test_func(Base *pb)
{
	pb->func();
//	pb->func_new();  //Error!

	if(typeid(* pb)==typeid(Derived)) //判断强制类型转换的合法性
	{
		Derived *pd=(Derived *)pb;
//		Derived *pd=dynamic_cast<Derived *>(pb);
//		Derived *pd=static_cast<Derived *>(pb);
//		Derived *pd=reinterpret_cast<Derived *>(pb);
		pd->func_new();
	}

	return;
}

void main()
{
	Base *pb;
	Derived d;

	pb=&d;

	test_func(pb);

	return;
}

/*
func() in Derived
func_new() in Derived
Press any key to continue
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?