关于c++模板的问题
//stack.h
#include <iostream>
using namespace std;
#define MAXSIZE 100
#ifndef STACK_H_H
#define STACK_H_H
template <class type> class data
{
public:
type element;
type min;
};
template <class T> class stack
{
public:
stack()
{
top = -1;
maxsize = MAXSIZE;
sk = new data<T>[MAXSIZE];
}
~stack()
{
delete sk;
}
void pop();
void push(T x);
void StackFront(T &x);
bool isEmpty()
{
if (-1 == top)
{
return true;
}
return false;
}
bool isFull()
{
if ((maxsize-1) == top)
{
return true;
}
return false;
}
private:
data<T> *sk;
int top;
int maxsize;
};
#include "stack.cpp"
#endif
//stack.cpp
template <class T> void stack<T>::push(T x)
{
if (isFull())
{
cerr << "the stack is full" << endl;
return;
}
if (isEmpty())
{
sk[++top].element = x;
sk[top].min = x;
}
else
{
sk[++top].element = x;
if (sk[top-1].min < x)
{
sk[top].min = sk[top-1].min;
}
else
{
sk[top].min = x;
}
}
}
template <class T> void stack<T>::pop()
{
if (isEmpty())
{
cerr << "the stack is empty" << endl;
return;
}
top--;
}
template <class T> void stack<T>::StackFront(T &x)
{
x = sk[top].min;
}
//main.cpp
#include <iostream>
#include "stack.h"
int main()
{
stack<int> ob;
ob.push(2);
ob.pop();;
return 0;
}
[解决办法]
微软的C++编译器不支持 模板的声明和实现 文件分离,也就是说模板的声明和实现都要在一个文件里写。。。。
[解决办法]
你需要把模板的全部在头文件中实现