mercredi 27 janvier 2021

Class inheritance but encounter redefinition error in C++

I'm learning C++ Data Structure, about implementing Stack using Array and Linked List. The array is default in C++ but I've constructed a Linked List class. The code below is my Linked List header file

#pragma once
#include "Node.h"
#include "Stack.h"
class LinkedList
{
public:
    LinkedList() {head = NULL;}
    Node* AddNode(int index, float x, bool doubly);
    int FindNodeIndex(float x);
    Node* FindNodeAddress(float x);
    void DeleteNode(float x);
    void DisplayList();
    
private:
    Node* head;
    friend class Stack;
};

which also used the Node header file, but it is not relevant here. Then I would like to implement stack using both array and linked list. Below is my Stack header file:

#pragma once

class Stack
{
public:
    Stack(int size = 10);
    bool IsEmpty() { return top == -1;}
    bool IsFull() { return top == maxTop;}
    double Top();
    void Push(const double x);
    double Pop();
    void DisplayStack();
    void Clear();
private:
    int maxTop;
    int top;
    double* values;
};

class Stack: public LinkedList
{
public:
    Stack(){}
    double Top()
    {
        if (!head)
        {
            std::cout << "The stack is empty." << std::endl;
            return -1;
        }
        else
            return head->data;
    }
    void Push(const double x) {AddNode(0,x);}
    void DisplayStack() { DisplayList();}
}

You can see in the Top() method, which is used to find the top element of the linked list, used the head variable (or explicitly, pointer of Node), where in the implementation of array, I have the same Top() method but it only use indexed array. The compiler give me this error message

Stack.h:20:7: error: redefinition of 'class Stack'
   20 | class Stack: public LinkedList

I knew I've probably made some mistake here, but I think it is necessary to write two Stack classes because they have different purpose, for example the Top() method cannot be used for both. Is it possible to combine both as one Stack class, then notify the compiler whether to use array or linked list?

Aucun commentaire:

Enregistrer un commentaire