C++多态性:检查子类的数据类型
可能的重复:
在 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 类对象的指针?
Possible Duplicate:
Finding the type of an object in C++
Hello,
I am sorry if it's a duplicate but I was not able to find answer to my question here.
Let's assume we have following class structure in 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); }
};
Now I have got a pointer to CPolygon object. How do I check if it's actually a pointer to the object of class CRectangle?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过检查
dynamic_cast(ptr)
是否返回非空来执行此操作,其中ptr
是指向CPolygon
的指针。然而,这要求基类 (CPolygon
) 至少有一个您可能需要的虚拟成员函数(至少一个虚拟析构函数)。You can do this by checking if
dynamic_cast<CRectangle*>(ptr)
return non-null, whereptr
is a pointer toCPolygon
. However this requires the base class (CPolygon
) to have at least one virtual member function which you probably need anyway (at least a virtual destructor).理想情况下,你不需要。您可以使用多态性来做正确的事情:
在 CPolygon 指针上调用
area()
,您将获得 CRectangle 的面积(如果它就是这样的话)。从 CPolygon 派生的所有内容都必须实现area()
,否则您将无法实例化它。Ideally, you don't. You use polymorphism to just do the right thing:
Call
area()
on your CPolygon pointer, and you'll get the area for a CRectangle if that's what it is. Everything derived from CPolygon will have to implementarea()
or you won't be able to instantiate it.你可以进行dynamic_cast:
但是向下转型自然是一种不好的做法,应该谨慎使用。在良好的设计中,您不关心指针的实际动态类型。
You can dynamic_cast it:
But naturally downcasting is a bad practice and should be used with caution. In a good design you don't care about the actual dynamic type of the pointer.
您可以对 CRectangle 执行动态转换,看看是否给出正确的结果。
You can perform a dynamic_cast to CRectangle and see if that gives a proper result or not.