C++ 模板类与头文件
生活随笔
收集整理的這篇文章主要介紹了
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++ 模板类与头文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 叫车服务算法
- 下一篇: 途家木鸟美团夏日折扣对垒,门槛低就一定香