dynamic_cast的妙用
class base
{
public:
void iAm(){cout<<"base\n";}
virtual ~base(){}
};
class derived: public base
{
public:
void iAm(){cout<<"derived\n";}
virtual ~derived(){}
};
void testclass(base *p)
{
//在这里想办法输出实际类名
//p有可能是base类型指针传进来也有可能是derived类型指针传进来
}
{
public:
void iAm(){cout<<"base\n";}
virtual ~base(){}
};
class derived: public base
{
public:
void iAm(){cout<<"derived\n";}
virtual ~derived(){}
};
void testclass(base *p)
{
//在这里想办法输出实际类名
//p有可能是base类型指针传进来也有可能是derived类型指针传进来
}
测试用例如下:
base b;
derived d;
testclass(&b);
testclass(&d);
derived d;
testclass(&b);
testclass(&d);
则输出为:
base
derived
——来自2Kgames实习生笔试题
这题,其实就是给定一个父类和子类,并创建一个指向类的指针,然后该指针已经被强制转换成了指向父类的指针,然后想让你用某种方法判断出该指针所指向的对象其实是个真正的父类对象,还是一个被强制当做父类的子类对象!
用dynamic_cast强制类型转换就能做到这一点,以下是解决方案:
解决方案
#include <iostream>
using namespace std;
class base
{
public:
void iAm(){cout<<"base\n";}
virtual ~base(){}
};
class derived: public base
{
public:
void iAm(){cout<<"derived\n";}
virtual ~derived(){}
};
void testclass(base *p)
{
//在这里想办法输出实际类名
//p有可能是base类型指针传进来也有可能是derived类型指针传进来
if( derived * temp = dynamic_cast<derived *>( p ) )
{
temp->iAm();
}
else
{
p->iAm();
}
}
int main(int argc, char* argv[])
{
base b;
derived d;
testclass(&b);
testclass(&d);
return 0;
}
using namespace std;
class base
{
public:
void iAm(){cout<<"base\n";}
virtual ~base(){}
};
class derived: public base
{
public:
void iAm(){cout<<"derived\n";}
virtual ~derived(){}
};
void testclass(base *p)
{
//在这里想办法输出实际类名
//p有可能是base类型指针传进来也有可能是derived类型指针传进来
if( derived * temp = dynamic_cast<derived *>( p ) )
{
temp->iAm();
}
else
{
p->iAm();
}
}
int main(int argc, char* argv[])
{
base b;
derived d;
testclass(&b);
testclass(&d);
return 0;
}
运行在VS2008上显示输出结果为:
base
derived
^_^ 成!