【问题标题】:Error: this declaration has no storage or type specifier错误:此声明没有存储或类型说明符
【发布时间】:2012-10-17 04:25:15
【问题描述】:

我收到此消息,其中包含 Node* 的所有内容(此声明没有存储或类型说明符)。有人可以帮忙,请给我正确的方向吗?

template <typename type>
Node* Stack<type>::pop() {
Node* retNode; // the node to be return
if(tos == NULL) {
    cerr << "*** Stack empty ***";
    exit(1);
}
else {
    retNode = tos; // store the location of tos
    tos = tos->getLink(); // move to new tos
    retNode->setLink(); // unlink the popped node from the stack
    size -= 1;
}
return retNode;
}

我确定它正在处理Node*,但我就是不知道是什么。

以下是我对堆栈类中使用的节点类的声明。如果您还需要我对堆栈类的声明,请告诉我,因为我看不到问题所在。

template <typename type>
class Node<type>{

private:
type data;
Node *link;

public:
Node(type p_item, Node *p_link);
type getData() const;
Node* getLink() const;
void setData(type p_data);
void setLink(Node *node);
};

【问题讨论】:

  • 在编译此代码之前,您必须在范围内声明 Node。那么,它在哪里?
  • 对不起,我一直在努力理解这个网站在评论部分放置代码的方法,但我仍然遇到问题。
  • 不要在 cmets 中发布该代码,只需编辑您的原始帖子。
  • 非常感谢。我没有意识到这一点,并认为人们希望我们对此发表评论。
  • 很明显,Node 是一个模板,所以您需要使用Node&lt;type&gt; * 而不是Node *(假设要使用的type 与您使用的Stack 相同)模板)。

标签: c++ templates compiler-errors


【解决方案1】:

Node 是类模板,因此不能使用NodeNode * 作为数据类型。您必须在尖括号中添加模板参数,例如Node&lt;int&gt;Node&lt;char&gt; * 等。

在您给出的具体示例中,以下内容似乎是合适的:

template <typename type>
Node<type>* Stack<type>::pop() {
  Node<type>* retNode;
  /* ... */
  return retNode;
}

即用于Stack 的相同类型参数也应该(可能)用于Node

另外两个注意事项:

  1. 看起来很奇怪,虽然Node 模板似乎实现了堆栈的内部数据结构,但堆栈的弹出函数返回了Node&lt;type&gt; * 指针。返回type 对象似乎更自然(并且封装更好,对堆栈用户来说更直观)。

  2. 当堆栈为空时,pop 函数调用exit(从而使整个进程停止)似乎也很奇怪。也许返回nullptr,或者一个虚拟对象,或者抛出一个异常(或类似的策略)会更合适。

【讨论】:

  • 它似乎正在工作并且错误消失了。非常感谢您的参与。我真的很感激!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
相关资源
最近更新 更多