【问题标题】:Why is Visual Studio forcing StackNode two different ways?为什么 Visual Studio 以两种不同的方式强制 StackNode?
【发布时间】: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&lt;DataType&gt; *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


【解决方案1】:

从您显示的代码来看,StackNode&lt;DataType&gt; 不正确,因为StackNode 不是类模板。

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

【讨论】:

  • 有趣的是,当我将光标悬停在 StackNode 上时,Visual Studio 说它来自 StackLinked::StackNode。然而编译器仍然接受它。这是我创建的唯一版本的 StackNode。
猜你喜欢
  • 1970-01-01
  • 2017-12-13
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
相关资源
最近更新 更多