简体   繁体   中英

C++ Adding a data member to a struct from another base class

Good Day. I am busy coding for a project at University and I would like to know how I can add a data member to a node struct (For a linked list), but the struct has been previously defined. I can't just define it all in the original struct as instructions state otherwise.

Here is my struct, located in ListAsSSL.h file:

struct node
{
     node* next;
     Object obj;
};

Can I do this in another header file:

struct node: node
{
    node* previous;
};

Thank you. I did just self-study the Decorator pattern, but it only shows how to do it with classes and not structs.

Thank you for the assistance. Richard

No you cannot extend a struct like that. Create a new struct with inheritance instead, like this:

struct node
{
     node* next;
     Object obj;
};

And in your other file:

struct newNode: node
{
    node* previous;
};

And in your client code, the code that accesses the struct, you have to use the new struct instead of the old one. Remember, this is what inheritance was built for in many cases: To add more features to an existing class!

Can you create a new struct? For example:

struct nodeV2
{
     Object obj;

     nodeV2* next;
     nodeV2* previous;
};

This seems to be the easiest way, to me. This way, you can keep the original struct, while not getting into inheritance.

All the best.

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