Possible Duplicate:
Finding the type of an object in C++
你好,
如果它是重复的,我很抱歉,但我无法在这里找到我的问题的答案。
假设我们在 c++ 中有以下类结构:
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
};
现在我有一个指向 CPolygon 对象的指针。如何检查它是否实际上是指向 CRectangle 类对象的指针?
最佳答案
您可以通过检查 dynamic_cast<CRectangle*>(ptr)
来做到这一点。返回非空值,其中 ptr
是指向 CPolygon
的指针.但是,这要求基类(CPolygon
)至少有一个您可能需要的虚成员函数(至少是一个虚析构函数)。
关于C++ 多态性 : Checking data type of sub class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4107145/