【发布时间】:2012-10-27 23:31:31
【问题描述】:
所以我最近写了一个基于链表的 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
如果需要任何其他详细信息。就问吧!感谢您的时间!
【问题讨论】:
-
我们可以看看你的班级声明吗?您的赋值运算符是否正确声明?
-
根据我的基本测试,g++ 4.7.2 似乎对
StackNode *temp;很满意 -
我用每个请求的类声明更新了我的问题。
标签: c++ visual-studio-2010 data-structures linked-list stack