调用模板类出现 undefined reference 错误的解决方法

 g++不支持模板类的分离编译,因此模板的实现最好都些在.h文件中,否则将出现undefined reference to XXXX 的错误。下面是一个出错的例子,解决方法就是将stack.cc中的代码移到stack.h中。


01
02
03 #ifndef __MY_STACK__
04 #define __MY_STACK__
05
06 #include <vector>
07 #include <stdexcept>
08
09 template <typename T>
10 class Stack {
11 public:
12     void push(T const&);
13     void pop();
14     T top() const;
15     bool empty() const {
16         return elems.empty();
17     }
18 private:
19     std::vector<T> elems;
20 };
21
22 #endif
23
24
25
26 #include "stack.h"
27
28 template <typename T>
29 void Stack<T>::push (T const& elem)
30 {
31     elems.push_back(elem);
32 }
33
34 template <typename T>
35 void Stack<T>::pop ()
36 {
37     if (elems.empty()) {
38         throw std::out_of_range("Stack<>::pop(): empty stack");
39     }
40     elems.pop_back();
41 }
42
43 template <typename T>
44 T Stack<T>::top () const
45 {
46     if (elems.empty()) {
47         throw std::out_of_range("Stack<>::top(): empty stack");
48     }
49     return elems.back();
50 }
51
52
53
54 #include <iostream>
55 #include "stack.h"
56
57 int main(void)
58 {
59     Stack<int> is;
60   
61     int i;
62
63     for (i=0i<10i++{
64         is.push(i);
65     } 
66
67     for (i=0i<12i++{
68         std::cout << is.top() <<std::endl;
69         is.pop();
70     } 
71
72     return 0;
73 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值