示例

#include <typeinfo>

class Shape{
    public:
        virtual ~Shape()=0;
};


class Circle : public Shape{};
class Square :
public Shape{};

void function(const Shape * s)
{
if (typeid(*s)==
typeid(Circle))
{
//do something for Circle
}
else if (typeid(*s)==typeid(Square))
{
//do something for Square
}
}

解决方案
使用返回唯一标识的虚拟 classOf() 函数实施类,或测试动态数据类型转换成功与否。

class Shape{
    public:
        virtual ~Shape()=0;
};

class Circle :
public Shape{};
class Square :
public Shape{};

void function(const Shape * s)
{
Shape *sh = const_cast<Shape*> (s);

if (dynamic_cast<Circle *>(sh)
)
{
//do something for Circle
}
else if (
dynamic_cast<Square *>(sh) )
{
//do something for Square
}
}