0

所以我最近写了一个基于链表的 Stack ADT 实现。但是,我不太确定为什么堆栈节点的声明方式之间存在一些差异。编译器非常生气,直到我为某些函数以某种方式编写它们时才会编译。我非常好奇为什么会这样。

这是编译器需要两种不同格式的两种不同方法。

这是编译器想要的我的析构函数StackNode *temp

template <typename DataType>
StackLinked<DataType>::~StackLinked() {
   StackNode *temp;
   while (top != 0) {
       temp = top;
       top = top->next;
       delete temp;
   }
}

这是编译器想要的赋值运算符重载StackNode<DataType> *temp

template <typename DataType>
StackLinked<DataType>& StackLinked<DataType>::operator=(const StackLinked& other) {
    if (this != &other) {
        StackNode<DataType> *newNode, *current, *last;

        if (top != 0) {
           StackNode<DataType> *temp;
           while (top != 0) {
               temp = top;
               top -> top->next;
               delete temp;
           }
        }

        if (other.top == 0) {
            top = 0;
        }
        else {
            current = other.top;
            top = new StackNode<DataType>;
            top->dataItem = current->dataItem;
            top->next = 0;
            last = top;
            current = current->next;

            while (current != 0) {
                newNode = new StackNode<DataType>;
                newNode->dataItem = current->dataItem;
                newNode->next = 0;
                last-> next = newNode;
                last = newNode;
                current = current->next;
            }
        }
    }
    return *this;
}

我不知道为什么会这样,但未知的事情困扰着我。

注意:我的 StackNode 类是 StackLinked 类的内部类。

编辑:类声明:

#ifndef STACKARRAY_H
#define STACKARRAY_H

#include <stdexcept>
#include <iostream>

using namespace std;

#include "Stack.h"

template <typename DataType>
class StackLinked : public Stack<DataType> {

public:

StackLinked(int maxNumber = Stack<DataType>::MAX_STACK_SIZE);
StackLinked(const StackLinked& other);
StackLinked& operator=(const StackLinked& other);
~StackLinked();

void push(const DataType& newDataItem) throw (logic_error);
DataType pop() throw (logic_error);

void clear();

bool isEmpty() const;
bool isFull() const;

void showStructure() const;

private:
class StackNode {
  public:
StackNode(const DataType& nodeData, StackNode* nextPtr);
DataType dataItem;
StackNode* next;
};

StackNode* top;
};

#endif  

如果需要任何其他细节。就问吧!感谢您的时间!

4

1 回答 1

0

从您显示的代码来看,StackNode<DataType>不正确,因为StackNode它不是类模板。

这让我觉得你有一个模板也被命名StackNode为编译器正在寻找的。去检查您的任何文件是否包含另一个版本的StackNode.

于 2012-10-28T00:42:58.993 回答