c++ - 如何向结构添加新成员

标签 c++ inheritance data-structures struct

这些是我拥有的函数和 Struct 声明,不允许我更改它们。

DerivedA giveDerivedA ();
DerivedB giveDerivedB ();

struct Base{
    QString elementId;
    QString elementType;
};

struct DerivedA : Base {
    int a;
    int b;
};

struct DerivedB : Base {
    int c;
    int d;
};

但我需要的是这样的:

struct DerivedA : Base {
    int a;
    int b;
    void create();
    QString doc;
};

如何将这些方法和成员添加到我得到的结构中?

我的第一个想法是:

struct myA: DerivedA {
    void create();
    QString doc;
};

你有什么建议吗?

编辑:第二个选择(已选择)

struct myA{
    void create();
    QString doc;
    private:
      DerivedA derivedA;
};

最佳答案

这类似于人们在扩展标准库类时遇到的问题。如果你的基类没有虚拟析构函数,你就不能安全地继承它。在这种情况下,您必须使用自由函数(无论如何首选)或组合。

否则,你所拥有的就是好的。

关于c++ - 如何向结构添加新成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3210343/

相关文章:

java - 对编译器处理继承和方法调用感到困惑

data-structures - 如何使用 BITMAP 存储电话号码?

c++ - 在 SPOJ INCSEQ 中获取 WA - 增加子序列

c++ - 在wxWidgets中创建一个全局的wxCriticalSection变量不好吗?

c++ - closesocket 线程安全吗?

c++ - 继承类为静态

c++ - 使用虚空函数但没有编译错误的类中的运行时错误

c - 优化 malloc 实现的隔离列表组织

c++ - 给定两组 xyz 坐标和 sag (a) 的值,我可以在 OpenGL 中的这些点之间绘制悬链线吗?

c++ - 如何打包/发送程序(Visual Studio 2013)