Ami*_*t S 14 c++ polymorphism object
可能重复:
在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); }
};
Run Code Online (Sandbox Code Playgroud)
现在我有一个指向CPolygon对象的指针.如何检查它是否实际上是指向类CRectangle对象的指针?
vit*_*aut 12
您可以通过检查dynamic_cast<CRectangle*>(ptr)返回非null 来执行此操作,其中ptr指针指向CPolygon.但是,这需要基类(CPolygon)至少具有一个您可能需要的虚拟成员函数(至少是一个虚拟析构函数).
理想情况下,你没有.你使用多态来做正确的事情:
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area() const = 0;
};
class CRectangle: public CPolygon {
public:
int area () const
{ return (width * height); }
};
Run Code Online (Sandbox Code Playgroud)
调用area()你的CPolygon指针,你将得到一个CRectangle的区域,如果它是这样的.从CPolygon派生的所有内容都必须实现,area()否则您将无法实例化它.