c++ 模板类不能分离编译

在.h文件中必须同时有模板的声明和明确的定义,不能在.cpp中却定义。

 1 #ifndef STACKTP_H_
 2 #define STACKTP_H_
 3 template <class Type, int MAX>
 4 class Stack
 5 {                                                                             
 6     private:
 7         Type items[MAX];
 8         int top;
 9     public:
10         Stack() { top =0;}
11         bool isempty() {return top ==0;}
12         bool isfull() { return top == MAX;}
13         bool push(const Type & item);
14         bool pop(Type & item);
15 };
16 
17 template <class Type, int MAX>
18 bool Stack <Type, MAX>::push(const Type & item)
19 {
20     if (top < MAX)
21     {
22         items[top++] = item;
23         return true;
24     }
25     else return false;
26 
27 }
28 
29 template <class Type, int MAX>
30 bool Stack <Type, MAX>::pop( Type & item)
31 {
32     if (top > 0)
33     {
34         item = items[--top] ;
35         return true;
36 
37     }
38     else return false;
39 
40 }
41 
42 
43 #endif

如果在.cpp中实现函数的定义则会包错

参考连接为

https://blog.csdn.net/u011846123/article/details/90674912

原文地址:https://www.cnblogs.com/miaorn/p/14254581.html