标签:
#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;
}
};
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;
cout << typeid(cp).name() << endl;
cout << typeid(*cp).name() << endl;
funcD(cp);
funcC(cp);
base *dp = new base;
funcC(dp);
funcD(dp);
system("pause");
return 0;
}
运行结果为:
class base *
class derived
derived
derived
base
base
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/wangfengfan1/article/details/47154883