没有继承的链表

时间:2018-11-09 23:12:26

标签: c++ inheritance linked-list

我用c ++创建了一个链表。首先,我创建了一个类Node,然后创建了另一个名为List的类。我的程序运行完美。问题是,我不理解为什么NodeList之间没有继承,以便List类可以访问Node的公共方法。
我进行了一些更改,并从List派生了Node及其工作原理。那么它如何在没有继承的情况下继承呢?

#include <iostream>
#include <stdlib.h>

using namespace std;

/* The Node class */
class Node
{
private:
    int object;
    Node * nextNode;

public:
//mutator and Accessor for Node values
    void set(int object)
    {
        this->object = object;
    }
    int get()
    {
        return object;
    }

//mutator and Accessor for Node Address
    void setNext(Node * nextNode)
    {
        this->nextNode = nextNode;
    }
    Node * getNext()
    {
        return nextNode;
    }
};


/* The List class */
class List : public Node
{
private:
    int size;   // List Size ( number of nodes )
    Node * headNode;    // address of starting node of list
    Node * currentNode; // address of Current node of list
    Node * lastCurrentNode; // address of previous node of list

public:
    /* Constructor */
    List()
    {
        headNode = new Node();          // creating new node and store its address in headNode  as its start of list
        headNode->setNext(NULL);    // the headNode is not connecting to any other node
        currentNode = NULL;             // as theres only head node so currentNode is empty
        lastCurrentNode = NULL;      //  Previous Node is also empty because there's only headNode
        size = 0;                               // Lisrs Size = 0 because theres no Value/data/object inside the list
    }

    /* add() class method */
add (int addObject)
{
    Node * newNode = new Node();    // creating/adding new node and store its address in newNode Pointer
    newNode->set(addObject);           // Add Value/data/object in the node just created

    if( currentNode != NULL )   // at first time when Current Node pointer is not pointing to any node in the list
    {
        newNode->setNext(currentNode->getNext());   // get adddress of node where current node will go and store that in the nextNode Pointer which is now called by our new node pointer so the addres that currentNode had now os taken and given to the new node
        currentNode->setNext( newNode );                  // address of new node we just created is now stored in current node
        lastCurrentNode = currentNode;                      // move Lastcurrent node to the current node position
        currentNode = newNode;                                 //   move currentNode pointer to the newNode we created;
    }
    // if current node is not pointing to any node (first time)
    else
    {
        newNode->setNext(NULL);             // new node we created will not point to any other next node because there's no one
        headNode->setNext(newNode);     //  head node now is pointing to the new node we created
        lastCurrentNode = headNode;      // lastCurrent node is now position to headNode so we can go back
        currentNode = newNode;             // current node is now position to the new node we created
    }
    size ++;        // as there's new new in the list increase its size to +1
}

/* get() class method */
    get()
    {
        if (currentNode != NULL)
        return currentNode->get();      // if current node is not null give the value where the current node is
    }

    /* next() class method */
    next()
    {
        if (currentNode == NULL)
        {
            return false;
        }

        lastCurrentNode = currentNode;  // move lastCurent node tot he position of current node
        currentNode = currentNode->getNext();       // move current node to the next node

        if (currentNode == NULL || size == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
friend void traverse(List list);
friend List addNodes();

};

/* Friend function to traverse linked list */
void traverse(List list)    // friend function will get the object of List class
{
    Node* savedCurrentNode = list.currentNode;  // create new node pointer and assign it the address of current node
    list.currentNode = list.headNode;                   // move current node to the headNode ( starting of the list)
    for(int i = 1; list.next(); i++)                               // while we dnt reached to the end of list or not get false from next function
    {
        cout << "\n Element " << i << "  =  " << list.get();        // traverse every node and display its value
    }
    list.currentNode = savedCurrentNode;            // after traversing the whole nodes in the list move the current node to the position where it was befor e
}

/* Friend function to add Nodes into the list */
List addNodes()
{
    List list;
    list.add(2);
    list.add(6);
    list.add(8);
    list.add(7);
    list.add(1);

    cout << "\n List size = " << list.size <<'\n';

    return list;
}

int main()
{
    List list = addNodes();
    traverse(list);
}

改编自Asker的评论:

  

有人能解释一下“第二类如何在没有继承的情况下使用第一类的public方法吗?第二类不必从第一类派生而来吗?能够指向基类(第一类)的方法?

1 个答案:

答案 0 :(得分:2)

在这种情况下,

继承是错误的事情 tm 。如注释中所述,继承为“ is-a”关系建模:

法拉利汽车
梅赛德斯汽车...都有四个轮子和n门。所以
普通汽车具有法拉利和梅赛德斯继承的四个轮子和n门。

但是列表(容器)肯定不是节点。从您的代码中,列表将具有:

int object ...列表的值是什么?没道理
指针nextNode ...列表的“下一个节点”是什么?另一个清单?没道理
函数set(int object)int get() ...设置/得到什么?清单的价值?没道理
函数setNext(Node * nextNode)Node* getNext() ...如上:列表的“下一个节点”是什么?没有道理。

您要应用的模式是“合成”,它为“ has-a”关系建模:

法拉利方向盘
奔驰有一个方向盘
普通汽车有一个方向盘

您的

列表有一个第一个节点。

。 o O(您的问题使我想到一位德国作家,他坚持要求WurstBrotWurst继承BrotSupermarket [sic])

btw:问题中显示的代码不应编译。几个函数缺少返回类型。

您应遵守Liskov Substitution Principle的说明,

  

在计算机程序中,如果S是[=继承自] T的子类型,则类型T的对象可以用类型S的对象替换(即类型T的对象可以用子类型S的任何对象代替),而无需更改程序的任何所需属性(正确性,执行的任务等)。

关于您的代码,List的c-tor已经使我迷失了:

List()
{
    headNode = new Node();     // why does an empty list have a Node thats its head?
    headNode->setNext(NULL);   // that is something the c-tor of Node should do
    currentNode = NULL;        // not sure what currentNode is supposed to be
    lastCurrentNode = NULL;    // contradicts my assumption from above that lastCurrentNode
                               // was a pointer to the last node of the List;
                               // you created a first Node so the last node should be
                               // pointing to headNode
    size = 0; // hm. Now you say your list is empty but you created a Node?
}