从超类指针C ++访问子类成员 [英] Accessing subclass members from a superclass pointer C++

查看:160
本文介绍了从超类指针C ++访问子类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组自定义类Student对象。 CourseStudent和ResearchStudent都继承自Student,而Student的所有实例都是其中一个。

I have an array of custom class Student objects. CourseStudent and ResearchStudent both inherit from Student, and all the instances of Student are one or the other of these.

我有一个函数来遍历数组,确定子类型每个学生,然后调用它们的子类型特定成员函数。

I have a function to go through the array, determine the subtype of each Student, then call subtype-specific member functions on them.

问题是,因为这些函数没有重载,所以在Student中找不到它们,所以编译器大惊小怪。

The problem is, because these functions are not overloaded, they are not found in Student, so the compiler kicks up a fuss.

如果我有一个指向学生的指针,有没有办法获得指向该学生子类型的指针?我是否需要在此处进行某种假冒操作以解决编译时错误?

If I have a pointer to Student, is there a way to get a pointer to the subtype of that Student? Would I need to make some sort of fake cast here to get around the compile-time error?

推荐答案

您需要动态转换:

Student * s = new ...;    // create student of some sort

if ( ResearchStudent * r = dynamic_cast<ReasearchStudent*>( s ) ) {
   r->ResFunc();
}
else if ( CourseStudent * c = dynamic_cast<CourseStudent*>( s ) ) {
   c->CourseFiunc();
}
else {
   throw "unknown student type";
}

请注意,这使用编译器维护的类型信息,前提是类具有至少一个虚函数 - 如果所有其他都失败,则使析构函数成为虚拟(因为它必须在这种情况下仍然是)。您应该始终更喜欢这种方法来维护自己的类型信息。

Note that this uses type information maintained by the compiler, provided the class has at least one virtual function - if all else fails, make the destructor virtual (as it must be in this case anway). You should always prefer this approach to maintaining your own type information.

这篇关于从超类指针C ++访问子类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆