当前位置:
首页 >
C++ 模板类与头文件
发布时间:2024/3/13
45
豆豆
生活随笔
收集整理的这篇文章主要介绍了
C++ 模板类与头文件
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
今天将模板类函数分成了声明和定义两个文件:
模板类的声明:
#pragma once#ifndef FIND_ITEM #define FIND_TIEM template <typename elemType> const elemType* find_item(const elemType* first,const elemType* last, const elemType& value);void print_hello();#endif模板类的定义
#include "iostream" void print_hello() {std::cout << "what the fuck"<<std::endl; } {if (!first || !last)return 0;for (; first != last; ++first)if (*first == value)return first;return 0;} template <typename elemType> const elemType* find_item(const elemType* first,const elemType* last, const elemType& value) {if (!first || !last)return 0;for (; first != last; ++first)if (*first == value)return first;return 0;}main函数:
#include <iostream> #include <vector> #include "find.hh" using namespace std;int main() {int a[] = {98,12,33,41,58,976,11,0,44};vector<int> vec_a(a, a + 7);const int* vec_index;vec_index = find_item(a,a+7, a[4]);print_hello();std::cout << "Hello World!\n"<<(vec_index - a); }单独编译定义的文件是可以通过的,但是整体编译在一起就死活不行了。
定位问题是,模板类只能是现在头文件中,是因为编译顺序决定的。
如果是普通类型函数的声明,在main中使用的时候,是需要留出函数的接口,在链接时链接就好了。
但是模板类,如果在链接的时候链接,会发现,main函数里所使用的的函数是具体的类型,但是模板定义的里面是template,链不上。所以应当将模板类的定义放到头文件中,编译器开始编译的时候就已经知道了函数的模板,在编译各个应用了模板函数的时候,直接替换掉就好了。
总结
以上是生活随笔为你收集整理的C++ 模板类与头文件的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 叫车服务算法
- 下一篇: C++经典算法题-循序搜寻法(使用卫兵)