【问题标题】:Template Class error C++模板类错误 C++
【发布时间】:2012-10-04 05:42:21
【问题描述】:

我正在学习如何制作模板类,我遵循了这个概念,但遇到了错误。我有一个类,我把它变成了一个模板,但我得到了以下错误;

simplestack.h(24): error C2955: 'SimpleStack' : 使用类模板需要模板参数列表

simplestack.h(9) : 参见“SimpleStack”的声明

simplestack.h(28):错误 C2244:“SimpleStack::push”:无法将函数定义与现有声明匹配

simplestack.h(12) : 参见 'SimpleStack::push' 的声明

这是我的代码:

const int MAX_SIZE = 100; 
template <typename T>
class SimpleStack
{
public:
  SimpleStack();
  SimpleStack & push(T value);
  T pop();

private:
  T items[MAX_SIZE];
  T top;
};
template <typename T>
SimpleStack<T>::SimpleStack() : top(-1)
{}

template <typename T>
SimpleStack &SimpleStack<T>::push(T value)
{
  items[++top] = value;
  return *this;
}

template <typename T>
T SimpleStack<T>::pop()
{
  return items[top--];
}

注意:每次我尝试将 MAX_SIZE 设置为 T 时,它都不会接受。感谢您的帮助。

【问题讨论】:

    标签: c++ list class templates arguments


    【解决方案1】:

    方法push 应该返回SimpleStack&lt;T&gt;&amp;,而不是SimpleStack&amp;

    【讨论】:

    • 在成员函数的定义中。在声明中,由于注入的类名,这并不重要。
    猜你喜欢
    • 2015-08-05
    • 2012-11-11
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2013-04-20
    相关资源
    最近更新 更多