问题描述
我有一个基类和两个从它派生的类.我在基类中有几个虚函数,因此我创建了一个指向基类的指针,并使用该指针访问这些方法.
I have one base class and two classes derived from it. I have several virtual functions in the base class so I create a pointer to the base class and use this pointer to access these methods.
现在,我想使用指向派生类对象的基类的指针访问派生类的成员变量(该变量在基类中不存在).
Now I want to access member variable of derived class (this variable is not present in the base class) using the pointer to base class which points to a derived class object.
可以做到吗?应该这样做吗?
推荐答案
为什么要访问派生类的界面?使用多态时,您无需关心基类引用/指针背后的内容. 如果这样做,通常就暗示了设计缺陷.
Why do you want to access the derived class' interface? When you use polymorphism, you shouldn't need to care about what's behind a base class reference/pointer. If you do, then that's usually a hint at a design flaw.
您要尝试的是开机类型". (如果B*
后面是D1
对象,则执行此操作,否则执行该操作.")接通类型正在规避多态性和不良信号.
What you are trying to do is a "switch-on-type". ("If behind B*
is a D1
object, do this, otherwise do that".) A switch-on-type is circumventing polymorphism and a bad sign.
注意:有一种方法可以执行此操作(dynamic_cast
),但是由于上述原因,我认为这是一种不好的做法,因此不再赘述.
Note: There is a way to do this (dynamic_cast
), but for the reasons mentioned above I consider this bad practice and won't elaborate on it.
这篇关于访问指向其基类的指针所指向的派生类对象的成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!