[英]Getting derived members from base class pointer
I was told that a base class pointer can point to any derived types of that base class. 有人告诉我,一个基类指针可以指向该基类的任何派生类型。 However, I need to access this derived class even though the argument is calling a pointer to base class.
但是,即使参数正在调用指向基类的指针,我也需要访问此派生类。
Here Meeting
is the derived type, ListItem
is the base type, CompareByInsertKey
is a mandatory purely virtual function in ListItem overriden by Meeting::CompareByInsertKey
, and Meeting
has a structure called thisdate
with a member year
. 这里
Meeting
是派生类型, ListItem
是基本类型, CompareByInsertKey
是ListItem中由Meeting::CompareByInsertKey
覆盖的强制性纯虚拟函数, Meeting
具有称为thisdate
的结构,具有成员year
。 In this instance, item_in_list would be a Meeting type but apparently the pointer still works even though it's a derived type. 在这种情况下,item_in_list将是会议类型,但是显然指针仍然是有效的,即使它是派生类型。
int Meeting::CompareByInsertKey(ListItem* item_in_list)
{
int compare = (*item_in_list).thisdate.year;
return compare;
}
How do I allow this method to take in a derived or base class argument and allow it to use derived class members? 如何允许此方法接受派生类或基类参数,并允许它使用派生类成员?
In other words, I need to access a derived type's private members in a method of that derived type. 换句话说,我需要以该派生类型的方法访问派生类型的私有成员。 The problem is that the
CompareByInsertKey
function must take a base class pointer in order to override the purely virtual ListItem::CompareByInsertKey
问题在于
CompareByInsertKey
函数必须采用基类指针才能覆盖纯virtual ListItem::CompareByInsertKey
Thanks, if you need any more information, please let me know 谢谢,如果您需要更多信息,请告诉我
You should use dynamic_cast
, like this: 您应该使用
dynamic_cast
,如下所示:
int Meeting::CompareByInsertKey(ListItem* item_in_list)
{
Meeting *meeting = dynamic_cast<Meeting*>(item_in_list);
// dynamic_cast returns a null pointer if the passed pointer is not
// of the requested type
if(meeting == 0) {
...
}
int compare = meeting->thisdate.year;
return compare;
}
The way you have it set up today, the only way I can see is to do a type check and cast using dynamic_cast
. 今天设置的方式,我唯一能看到的就是使用
dynamic_cast
进行类型检查和dynamic_cast
。 This ensures that mismatched types are not passed in. 这样可以确保不传递不匹配的类型。
int Meeting::CompareByInsertKey(ListItem* item_in_list)
{
Meeting* meeting = dynamic_cast<Meeting*>(item_in_list);
if(NULL != meeting)
{
int compare = meeting->thisdate.year;
return compare;
)
else // return error value
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.