2012-10-27 45 views
0

所以我最近写了一个基于链表实现Stack ADT的实现。但是,我不太确定为什么Stack的节点如何声明有差异。编译器变得非常生气,直到我为某些函数编写某种方法才会编译它。我非常好奇为什么会出现这种情况。为什么Visual Studio强制StackNode有两种不同的方式?

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

这里是我的析构函数,编译器想要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 

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

+0

我们能否看到您的类声明?您的分配运营商是否正确申报? –

+0

通过我的基本测试g ++ 4.7.2似乎很满意'StackNode * temp;' – Neil

+0

我用每个请求的类声明更新了我的问题。 –

回答

0

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

这让我觉得你有一个编译器发现的名为StackNode的模板。去检查你的任何文件是否包含StackNode的另一个版本。

+0

有趣的是,当我将鼠标悬停在StackNode上时Visual Studio说它来自StackLinked :: StackNode。然而编译器仍然接受它。这是我创建的StackNode的唯一版本。 –

相关问题