//一道笔试题
//考察RTTI的基本知识, 运行时类型识别
//还要打开VC编译器的RTTI功能
//Project / Settings/ C/C++ /Catogory选C++ language就看到那个选项了
#include <iostream>
#include <typeinfo>
using namespace std;
class base
{
public:
virtual void funcA() {cout << "base" << endl;}
};
class derived : public base
{
public:
virtual void funcB() {cout << "derived" << endl;}
};
//要求func能够输出形参的真实类型,下面两个func都可以
//funcC是用dynamic_cast类型转换是否成功来识别类型
//dynamic_cast必须要在有虚函数的hierarchy里进行
void funcC(base *p)
{
derived *dp = dynamic_cast<derived*>(p);
if(dp != NULL)
dp->funcB();
else
p->funcA();
}
//funcD用typeid操作符
void funcD(base *p)
{
derived *dp = NULL;
if (typeid(*p) == typeid(derived))
{
dp = static_cast<derived*>(p);
dp->funcB();
}
else
p->funcA();
}
int main()
{
base *cp = new derived;
funcD(cp);
funcC(cp);
base *dp = new base;
funcC(dp);
funcD(dp);
return 0;
}
posted on 2007-07-31 17:10
rebol 阅读(1284)
评论(0) 编辑 收藏 引用 所属分类:
Technical Gemes