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;
The compiler gives me the following error: "struct ListAsSLL::node has no member 'next'"
at my temp->next
line.
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
. 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. 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:
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. And since you are only accessing obj
, this is probably what you wanted.
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:
BasicNode* basicNode = static_cast<BasicNode*>(head);
您应该声明head为
node* head...;
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.