📄 demo_type_cast_6_all_test.cpp
字号:
//***********************************************************
// 使用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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -