当 class 的成员存储为没有此类方法的父 class 的对象时,如何访问它?

How to access a member of a class when it is stored as a object of a parent class that has no such method?

我有一个层次结构,例如:

Element
|_Resitance
|_DC Voltage Source
|_AC Voltage Source
|_AC Current Source
|_DC Current Source
|_DynamicElement
|  |_Inductor
|  |_Capacitor
|_SwitchingDevices
|  |_Switch
|  |_Diode
.
.
.

由于我的输入可以是其中的任何一个列表,因此它们都被插入到 std::vector<Element*> 中。问题是二极管、开关和电压源有一个我必须访问的 ID 成员。

我希望能够 运行 *(*Element).ID 或类似的东西,当我确定该元素是具有此类成员的子class 时。

我真的不想在元素 class 中包含 ID 成员,因为这是经常发生的事情,class 会有很多不合适的成员。

将虚拟析构函数添加到基 class 并使用 dynamic_cast<> 派生 class 以访问其成员。如果对象不是您转换到的类型的实例,dynamic_cast 通过引用将抛出异常,并且在相同情况下通过指针 dynamic_cast 将 return nullptr

示例:

class Element
{
    ...
    virtual ~Element() = default;
};

...

Element * el = new Diode();
Diode * d = dynamic_cast<Diode *>(el);
if (d) {
// ok, this is diode
}