简体   繁体   English

C ++继承链表

[英]C++ inheritance of linked list

class LinkedList{
    public:
    int data;
    LinkedList *next;
};

class NewLinkedList: public LinkedList{
    public:
    int data2;
};

When I use NewLinkedList , its next is still a pointer to LinkedList instead of NewLinkedList , so that I cannot access newlinkedlist.next->data2 without type casts. 当我使用NewLinkedList ,它的next仍然是指向LinkedList而不是NewLinkedList的指针,因此我无法访问newlinkedlist.next->data2而没有类型转换。 ( newlinkedlist is an object of NewLinkedList .) newlinkedlist是的目的NewLinkedList 。)

How can I design these two classes to avoid this problem? 我如何设计这两个类来避免这个问题?

Is there something like SELF_TYPE *next; SELF_TYPE *next;是否有类似SELF_TYPE *next;东西SELF_TYPE *next; and it becomes the type of derived class itself automatically when it is inherited? 它继承后会自动成为派生类本身的类型吗?

You can use a template: 您可以使用模板:

template <typename T>
class LinkedList{
public:
    int data;
    T * next;
};

class NewLinkedList: public LinkedList<NewLinkedList>{
public:
    int data2;
};

This technique is known as the Curiously recurring template pattern (CRTP) 这种技术被称为奇怪的重复模板模式(CRTP)

To improve the design, your LinkedList class should not contain any data other than what is needed for the linked list mechanism : it should be a base class only. 为了改进设计,您的LinkedList类不应包含除链表机制所需的数据之外的任何数据:它应该只是一个基类。 Then you subclass it as above with specialized classes. 然后使用专门的类将其子类化为上面的子类。

I would suggest, make the parent class as abstract and make the data members private(in most of the cases, that should be done; unless you have some really good reason not to do so) and add abstract functions to access these members. 我建议,将父类设为抽象,并使数据成员成为私有(在大多数情况下,应该这样做;除非你有一些非常好的理由不这样做)并添加抽象函数来访问这些成员。 That would be a good design and would solve your problem as well. 这将是一个很好的设计,也可以解决你的问题。

Lets suppose what you wish to achieve is possible. 让我们假设您希望实现的目标是可能的。

Consider: 考虑:

class AveryNewLinkedList: public LinkedList{
    public:
    int data2;
};

Will next be of a type AveryNewLinkedList or NewLinkedList ? nextAveryNewLinkedList类型还是NewLinkedList

The compiler does not know - nor do you. 编译器不知道 - 你也不知道。

So inheritance means you get bits from your parents and add to them - but the parents do not get anything from you! 因此,继承意味着你从父母那里得到一些东西并添加到他们身上 - 但父母却从你那里得到任何东西!

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

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