【发布时间】:2012-11-07 11:46:19
【问题描述】:
可能重复:
Why can templates only be implemented in the header file?
Why should the implementation and the declaration of a template class be in the same header file?
我正在做一个需要我的“堆栈”来保存数据的项目。但我不想为每个文件类型编写不同的版本(我不想使用向量)。
所以我正在尝试使用 模板类,这是我的代码:
StructStack.h
#ifndef STRUCTSTACK_H_
#define STRUCTSTACK_H_
template <class AnyType> class StructStack {
StructStack();
~StructStack();
struct Element {
Element *pointer;
AnyType value;
};
Element *pointerToLastElement;
int stackSize;
int pop();
void push(int value);
int size();
};
#endif
StructStack.cpp
#include "stdafx.h"
#include "StructStack.h"
#include <iostream>
using namespace std;
template <class AnyType> void StructStack<AnyType>::StructStack() {
//code
}
template <class AnyType> void StructStack<AnyType>::~StructStack() {
//code
}
template <class AnyType> AnyType StructStack<AnyType>::pop() {
//code
}
template <class AnyType> void StructStack<AnyType>::push(AnyType value){
//code
}
template <class AnyType> AnyType StructStack<AnyType>::size() {
//code
}
如果我尝试编译这两个文件,我会遇到一堆编译错误。我在网上看到,在多文件项目中创建模板类有点困难。
那么如何做到这一点呢?
【问题讨论】: