[英]Class inheritance but encounter redefinition error in C++
我正在學習 C++ 數據結構,關於使用數組和鏈表實現堆棧。 該數組在 C++ 中是默認的,但我構建了一個鏈接列表 class。 下面的代碼是我的鏈接列表 header 文件
#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;
};
它也使用了節點 header 文件,但這里不相關。 然后我想同時使用數組和鏈表來實現堆棧。 下面是我的堆棧 header 文件:
#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();}
}
在Top()方法中可以看到,該方法用於查找鏈表的頂部元素,使用了head
變量(或明確地,Node的指針),其中在數組的實現中,我有相同的Top()方法,但它只使用索引數組。 編譯器給我這個錯誤信息
Stack.h:20:7: error: redefinition of 'class Stack'
20 | class Stack: public LinkedList
我知道我可能在這里犯了一些錯誤,但我認為有必要編寫兩個 Stack 類,因為它們有不同的用途,例如 Top() 方法不能同時用於兩者。 是否可以將兩者合並為一個堆棧 class,然后通知編譯器是使用數組還是鏈表?
嗨,正如@Some_programmer_dude 所說
類不能“重載”,如果它們在同一個命名空間中定義,它們必須具有不同的名稱。
對於這種情況,我會使用多態性。 因此,我們定義了一個名為 Stack 的基礎 class,然后將創建另外兩個名為 LinkedListStack 和 ArrayStack 的類,它們都派生自 Stack。
// abstract class Stack
class Stack
{
public:
Stack(int size = 10);
virtual bool IsEmpty() = 0; // pure virtual function
virtual bool IsFull();
virtual double Top();
virtual void Push(const double x);
virtual double Pop();
virtual void DisplayStack();
virtual void Clear();
protected:
int maxTop;
int top;
double* values;
};
可以看到,Stack 有一個成員方法virtual bool IsEmpty() = 0;
,這被稱為純虛擬 function 沒有任何定義,這將導致我們的 class 成為抽象基礎 class。
抽象基類是只能作為基類使用,不能實例化的類。 由於我們不想實例化堆棧 class,我們想要實例化 LinkedListStack 或 ArrayStack。
然后對於每個派生類(LinkedListStack 和 ArrayStack),我們將定義它們的基本 class 虛函數。
class LinkedListStack: public Stack
{
public:
LinkedListStack();
bool IsEmpty() { return !head; }
double Top()
{
if (IsEmpty())
{
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(); }
/* define remaining base member methods. */
}
class ArrayStack : public Stack
{
public:
ArrayStack(int size = 10);
bool IsEmpty() { return top == -1; }
bool IsFull() { return top == maxTop; }
/* define remaining base member methods. */
};
查看這個驚人的C++ 教程,它教授虛函數和多態性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.