简体   繁体   English

C ++继承的结构

[英]C++ Inherited Structs

I am attempting to decorate a node struct in order to allow for single/double linked lists. 我试图装饰节点结构,以便允许单/双链表。 I have the following code: 我有以下代码:

    struct node
    {           
        Object* obj;
    };

    struct BasicNode: node
    {
            node* next;
    };

When I use the following code, I get an error: 当我使用以下代码时,出现错误:

temp->next = new BasicNode;
    temp = temp->next;

I have defined head as node* head; 我将head定义为node* head;

The compiler gives me the following error: "struct ListAsSLL::node has no member 'next'" at my temp->next line. 编译器给我以下错误:在我的temp->next行中, "struct ListAsSLL::node has no member 'next'"

What have I done wrong? 我做错了什么? Or was I wrong to do struct inheritance? 还是我做结构继承错了? Thank you for your time and assistance. 感谢您的时间和协助。

head is of type BasicNode . head的类型为BasicNode BasicNode inherits node which means that if you want to assign to head you need at least a BasicNode which isn't the case here. BasicNode继承了node ,这意味着如果要分配给head ,则至少需要一个BasicNode ,在这里不是这种情况。 You need an explicit cast (known as downcasting, parent to child class) if you know temp is of type BasicNode and you want to use it: 如果您知道temp的类型为BasicNode并且要使用它,则需要显式BasicNode转换(称为向下转换,从父级转换到子级):

head = static_cast<BasicNode*>(temp);

Upcasting (from child to parent class) however doesn't require an explicit cast. 向上转换(从子类到父类)不需要显式的强制转换。 For example, if you made head a type of node instead, you wouldn't have to cast it. 例如,如果将head设置为node类型,则无需强制转换。 And since you are only accessing obj , this is probably what you wanted. 而且由于您仅访问obj ,所以这可能就是您想要的。

node* head = //something..;

//later on..
node* temp = new BasicNode;
temp->obj = nl;
head = temp;

Then later on, if you somehow still know head contains a derived object like BasicNode you can always explicitly cast it again: 然后,如果您仍然以某种方式知道head包含派生对象(例如BasicNode ,则可以始终再次将其BasicNode

BasicNode* basicNode = static_cast<BasicNode*>(head);

您应该声明head为

node* head...;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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