简体   繁体   中英

How to Add New Members to Struct

These are functions and Struct declarations I have, and I'm not allowed to change them.

DerivedA giveDerivedA ();
DerivedB giveDerivedB ();

struct Base{
    QString elementId;
    QString elementType;
};

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

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

But what I need is something like this:

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

How can I add these method and member to structs I got?

My first idea is:

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

Do you have any suggestion?

Edit: 2nd Alternative(Choosed)

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

This is similar to the problem people have extending standard library classes. If your base class doesn't have a virtual destructor, you can't safely inherit from it. In that case, you must either use free-functions (preferred anyway), or composition.

Otherwise, what you have there is good.

使用组合或继承,具体取决于类之间的关系类型(例如,参见有效C ++中的第32和38项)。

那是行不通的,那就是您这样做的方式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM