类模板和引用返回类型
Class Template and Reference Return Type
长期读者,第一次海报!
在我开始之前有几点评论:我不是在寻找任何人为我做我的工作,我只需要一点指导。另外,我已经做了相当多的谷歌搜索,但我还没有找到任何解决方案。
我有一个班级作业,涉及为以下类创建模板:
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) {...}
相关文章:
- 将返回类型专用化为 void 或 const 左值引用
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 将成员函数的返回类型引用到C++中的自定义类
- 具有引用返回类型的重写方法上的协变返回类型无效
- 直接在 C++ 中将值分配给引用返回类型
- 为什么作为返回类型的右值引用不能初始化非常量引用?
- std::function 中不允许引用返回类型吗?
- 为什么类的赋值运算符的返回类型通常是非常量(而不是常量)引用?
- 自动返回类型不推断引用
- 从具有引用返回类型的函数返回什么
- 字符串和引用返回类型 C++?
- 模板引用折叠正在删除常量引用返回类型的cv限定符
- C++,从具有引用返回类型的函数返回什么以指示错误
- 字符串的decltype和const引用返回类型
- 类模板和引用返回类型
- 我可以在引用返回类型中返回指针吗
- 指针与引用返回类型
- 为什么我不能用非引用返回类型定义运算符=?
- c++中引用返回类型和指针返回类型有什么区别?