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

查看:53
本文介绍了从基类指针 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.

如果我有一个指向 Student 的指针,有没有办法获得指向该 Student 的子类型的指针?我是否需要在这里进行某种假转换来解决编译时错误?

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->CourseFunc();
}
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 anyway). You should always prefer this approach to maintaining your own type information.

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

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