且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问指向其基类的指针所指向的派生类对象的成员变量

更新时间:2023-02-15 07:49:24

为什么要访问派生类的界面?使用多态时,您无需关心基类引用/指针背后的内容. 如果这样做,通常就暗示了设计缺陷.

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.