【问题标题】:Using a template for a stack implementation; "name followed by :: must be a class or namespace"使用模板实现堆栈; “名称后跟 :: 必须是类或命名空间”
【发布时间】:2020-02-22 01:12:00
【问题描述】:

stack.h

template <class DataType>
class Stack {
private:
    int * topPtr;
public:
    Stack();    //constructor; initializes top to nullptr
    void push();    //adds a node
    void pop();     //removes most recently added node
};

到目前为止,stack.cpp

#include "stack.h"
//using namespace std;
template <class DataType>
Stack::Stack() {
    topPtr = nullptr;
}

Stack:: 带有错误“名称后跟 :: 必须是类或命名空间”下划线。如果相关,我正在使用 VS Code。

我只想有一个通用的堆栈实现,但我不确定为什么会出现这个错误?谢谢!

【问题讨论】:

标签: c++


【解决方案1】:

类外定义的语法是:

template <class DataType>
Stack<DataType>::Stack() : topPtr{nullptr} {}
//    ^^^^^^^^

【讨论】:

  • 这行得通,谢谢!不知何故,我在查看参考资料时错过了该语法。
  • 但正如评论中所说,当您将模板定义放入 cpp 时,您可能会遇到其他问题。
  • 所以我应该把实现移到头文件中;对吗?
  • 是的。模板定义应该是内联的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-20
  • 2020-02-02
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
相关资源
最近更新 更多