一、基本用法
类模板是用来生成类的蓝图,声明的方法都和函数模板类似:
1 2 3 4 5 6 |
template <typename T> class CTest { CTest(); ~CTest(); }; |
和函数模板不同的是,编译器无法为类模板推断参数类型,使用类模板必须手动通过尖括号指定。
1 2 3 |
CTest<int> t; vector<int> v; ... |
声明成员函数:
1 |
void CTest::test(int n); |
实现成员函数:
1 2 3 4 5 |
template <typename T> void CTest<T>::test(int n) { ... } |
要注意的是实现成员函数的时候域描述符前的应该是CTest<T>
而不是CTest
。
二、使用类模板的注意事项
使用类模板时成员函数的声明和定义都必须在一个文件中,推荐写在.h
头文件中。
如果把.h
和.cpp
分开在运行时将会出现错误:
vs 中的错误
1 |
"public: __thiscall CBinNode<int>::~CBinNode<int>(void)" (??1?$CBinNode@H@@QAE@XZ),该符号在函数 _main 中被引用 2_class_template G:\code\cpp\8-oop\2_function_template\main.obj 1 |
g++中的错误
1 2 3 4 |
/usr/lib/../lib64/crt1.o: In function `_start': (.text+0x20): undefined reference to `main' collect2: error: ld returned 1 exit status make: *** [build] Error 1 |
具体为什么只能放在一个文件中的原因至今不知,百度也没有找到一个觉得靠谱的理由,暂且留下这个坑了我一晚上的问题吧。
评论