最近按照书本写了下模板类,熟悉下其使用方法。按照以往的编程风格,我们会把类的声明写在头文件中,而把类的实现部分写在cpp头文件中。
然而对于模板类,这种做法最容易遇到一个奇怪的问题,具体描述如下:
编程环境:VC6.0
语言: c++
情况一:把模板类的声明和定义都写在头文件中时,编译通过,且正常运行。
情况二:当声明和定义分开写时,main.cpp 里头引入模板类的头文件则编译通过,当build时有错误。
情况三:当声明和定义分开写时,main.cpp 里头引入模板类的cpp文件则编译通过,build时也正常,可以正常运行。
stack.h 文件:
#ifndef STACK_H
#define STACK_H
#define DEFAULT_SIXE 20
template <class Elem>
class Stack
{
private:
int top;
Elem* listArray;
int maxSize;
public:
Stack(int size = DEFAULT_SIXE)
{
maxSize = size;
listArray = new Elem[maxSize];
top = 0;
}
~Stack(){ delete[] listArray; }
void clear();
bool push(const Elem& data);
bool pop(Elem& data);
bool topValue(Elem& data) const;
int length() const { return top; }
};
#endif
stack.cpp文件:
#include "stack.h"
template <class Elem>
void Stack<Elem>::clear()
{
top = 0;
}
template <class Elem>
bool Stack<Elem>::push(const Elem& data)
{
if (top == maxSize)
{
return false;
}
listArray[top++] = data;
return true;
}
template <class Elem>
bool Stack<Elem>::pop(Elem& data)
{
if (top == 0)
{
return false;
}
data = listArray[--top];
return true;
}
template <class Elem>
bool Stack<Elem>::topValue(Elem& data) const
{
if (top == 0)
{
return false;
}
data = listArray[top-1];
return true;
}
main.cpp文件:
#include "stack.h"
#include <iostream.h>
int main()
{
Stack<int> s(3);
s.push(23);
s.push(34);
s.push(2);
int r;
s.pop(r);
cout<<r<<endl;
return 0;
}