[英]Building template Stack structure with vector c++
我正在C ++中基于矢量实现模板化的Stack结构。 我不确定我的代码有什么问题。
堆栈
#ifndef STACK_H_
#define STACK_H_
#include <vector>
using namespace std;
template <class T>
class Stack {
public:
Stack();
virtual ~Stack();
bool empty();
int size();
void push(T pushvar);
T pop();
private:
std::vector<T> container;
};
#endif /* STACK_H_ */
Stack.cpp
#include "Stack.h"
#include <vector>
//template <class T>
Stack::Stack()
:container(0)
{
}
Stack::~Stack() {
// TODO Auto-generated destructor stub
}
bool Stack::empty(){
return (container.empty());
}
甚至在从主体调用任何东西之前,Eclipse都会给我一些错误。 但我将举一个示例性的主要内容:
#include <iostream>
#include "Stack.cpp"
using namespace std;
int main() {
Stack<int> s;
cout << s.empty();
return (0);
}
编译器返回以下错误:
Description Resource Path Location Type
'container' was not declared in this scope Stack.cpp /PracticeCpp/src line 23 C/C++ Problem
'template<class T> class Stack' used without template parameters Stack.cpp /PracticeCpp/src line 22 C/C++ Problem
invalid use of template-name 'Stack' without an argument list Stack.cpp /PracticeCpp/src line 12 C/C++ Problem
invalid use of template-name 'Stack' without an argument list Stack.cpp /PracticeCpp/src line 18 C/C++ Problem
Member declaration not found Stack.cpp /PracticeCpp/src line 12 Semantic Error
Member declaration not found Stack.cpp /PracticeCpp/src line 18 Semantic Error
Member declaration not found Stack.cpp /PracticeCpp/src line 22 Semantic Error
Method 'empty' could not be resolved Stack.cpp /PracticeCpp/src line 23 Semantic Error
Symbol 'container' could not be resolved Stack.cpp /PracticeCpp/src line 13 Semantic Error
我知道我还没有意识到头文件中声明的所有方法,但这不是我的问题。 在继续了解它们之前,我想了解我在哪里错了?
我遵循了答案中的建议,但仍然无法理解仍然存在的错误。 我将模板实现移至标题。 为了避免混淆,我删除了其他未实现的方法。 现在,我的.cpp文件为空。 我的新头文件:
#ifndef STACK_H_
#define STACK_H_
#include <vector>
template <class T>
class Stack {
private:
std::vector<T> container;
public:
template <typename T>
Stack<T>::Stack() : container(0)
{
}
template <class T>
bool Stack::empty() {
return container.empty();
}
};
#endif /* STACK_H_ */
定义应该是
template <typename T>
Stack<T>::Stack() : container(0)
{
}
而且不在.cpp中
从来没有声明过Stack::empty()
方法,而是声明了Stack<T>::empty()
。 彼此的构造函数,运算符和方法也是如此。 将模板声明添加到每个实现中以解决此错误。 请注意,错误消息通过说“无效使用没有参数列表的模板名称'Stack'来提示错误。
范例:
template<class T> bool Stack<T>::empty() {
return container.empty();
}
模板方法的实现应包含在头文件中。 看到这个问题 。
编辑:
关于您的最新示例,您混合了两种解决方案。 尝试:
#include <vector>
template <class T>
class Stack {
private:
std::vector<T> container;
public:
Stack() : container(0)
{
}
bool empty() {
return container.empty();
}
};
要么
#include <vector>
template <class T>
class Stack {
private:
std::vector<T> container;
public:
Stack();
bool empty();
};
template<class T>
Stack<T>::Stack() : container(0)
{
}
template<class T>
bool Stack<T>::empty()
{
return container.empty();
}
在第一个解决方案中,您将在类的定义内定义函数。 编译器知道您正在使用Stack<T>
类,因此您不必提醒它。 在第二个解决方案中,函数是在类外部定义的。 在这里,您必须指定要定义的类的empty
方法和构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.