类模板和引用返回类型

Class Template and Reference Return Type

本文关键字:引用 返回类型      更新时间:2023-10-16

长期读者,第一次海报!

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

我有一个班级作业,涉及为以下类创建模板:

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;
}

很抱歉代码粘贴过多!

Make it

template <class T>
SimpleStack<T>& SimpleStack<T>::push(T value) {...}