类模板和引用返回类型

时间:2013-09-22 04:00:46

标签: c++

长期读者,第一次发布海报!

在我开始之前的一些评论:我不是在寻找任何人为我做我的工作,我只需要一些指导。此外,我已经做了相当多的谷歌搜索,我还没有找到任何解决方案。

我有一个类分配,涉及为以下类创建模板:

class SimpleStack
{
public:
  SimpleStack();
  SimpleStack& push(int value);
  int pop();

private:
  static const int MAX_SIZE = 100;
  int items[MAX_SIZE];
  int top;
};

SimpleStack::SimpleStack() : top(-1)
{}

SimpleStack& SimpleStack::push(int value)
{
  items[++top] = value;
  return *this;
}

int SimpleStack::pop()
{
  return items[top--];
}

SimpleStack& push(int value)外,其他所有内容似乎都有效:

template <class T>
class SimpleStack
{
public:
  SimpleStack();
  SimpleStack& push(T value);
  T pop();

private:
  static const int MAX_SIZE = 100;
  T items[MAX_SIZE];
  int top;
};

template <class T>
SimpleStack<T>::SimpleStack() : top(-1)
{}

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

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

我在SimpleStack& push(int value)的定义上一直遇到以下错误:“使用类模板需要模板参数列表,”和“无法将函数定义与现有声明匹配。”

如果它有帮助,这是主要的:

#include <iostream>
#include <iomanip>
#include <string>
#include "SimpleStack.h"
using namespace std;

int main()
{
  const int NUM_STACK_VALUES = 5;
  SimpleStack<int> intStack;
  SimpleStack<string> strStack;
  SimpleStack<char> charStack;

  // Store different data values
  for (int i = 0; i < NUM_STACK_VALUES; ++i)
  {
    intStack.push(i);
    charStack.push((char)(i + 65));
  }
  strStack.push("a").push("b").push("c").push("d").push("e");

  // Display all values
  for (int i = 0; i < NUM_STACK_VALUES; i++)
    cout << setw(3) << intStack.pop();
  cout << endl;

  for (int i = 0; i < NUM_STACK_VALUES; i++)
    cout << setw(3) << charStack.pop();
  cout << endl;

  for (int i = 0; i < NUM_STACK_VALUES; i++)
    cout << setw(3) << strStack.pop();
  cout << endl;

  return 0;
}

对于过多的代码粘贴感到抱歉!

1 个答案:

答案 0 :(得分:1)

成功

template <class T>
SimpleStack<T>& SimpleStack<T>::push(T value) {...}
相关问题