C 中模板類的宣告和實現分離問題

2021-08-07 13:26:10 字數 1515 閱讀 3375

有兩種方法

第1種:使用 .tpp 檔案實現類模板的介面與實現的檔案分離

在.h檔案中放介面,在.tpp檔案中放實現,但這種方法得在.h檔案中,類的定義下面通過#include包含」.tpp」檔案,如下:

檔案:放類模板的介面

#pragma once

templateclass templateclass

void print();//需實現的方法

private:

t data;

};#include "testtemplateclass.tpp"

//包含.tpp檔案

/**(其實,在這種情況下,實現檔案:testtemplateclass.tpp檔案,不一定要取這個名字,可以隨便取個名字,如: abc.t、 xyz.f等都可以,上述一行**的實際作用就是直接將**包含進去.h檔案中)

*/

檔案:放實現

template

void templateclass::print()

檔案:測試

#include

#include"testtemplateclass.h"

int main(int argc, char **argv)

第2種:使用顯式宣告實現類模板的介面與實現的檔案分離

在.h檔案中放介面,在.cpp檔案中放實現,然後在該.cpp檔案中顯式的宣告要使用的模板類例項,如下:

檔案:放類模板的介面

#pragma once

templateclass templateclass

void print();

private:

t data;

};//注意,使用這種方式,不需要通過#include來包含實現檔案

檔案:放實現

#include"testtemplateclass.h"

#include

template

void templateclass::print()

template

class templateclass;//顯式的宣告要使用的類模板的例項

template

class templateclass;//顯式的宣告要使用的類模板例項

/**(如果main.cpp檔案中需要用到 templateclass,那麼只需要在testtemplateclass.cpp檔案中新增一行**:template class templateclass;)

*/

檔案:測試

#include

#include"testtemplateclass.h"

int main(int argc, char **argv)

C 類模板的宣告和實現不能分離

也許你具有良好的程式設計習慣,在定義乙個類的時候總會把宣告和實現分離開,位於不同的檔案中。比如你定義乙個類a,首先建立乙個.h檔案,如下 class a 接下來你建立乙個.cpp檔案實現類的宣告,如下 include classa.h include a a int b void a show a ...

C 類模板的宣告與實現分離

第一次寫博文,本人才疏學淺,以現在的實力寫下這些東西,內容上可能會出現錯誤和不嚴謹之處,但是為了以後自己的回顧和總結,覺得自己應該在錯誤中前進,呵呵。如若讀者不幸搜尋到本人文章,請你們以懷疑的態度去閱讀。最近在實現鏈式佇列資料結構時,發現類模板的宣告與實現分離開 採用傳統的.h檔案和對應的.cpp檔...

類模板不能讓宣告和實現分離

寫模板類的時候出的問題,調了一晚上,就是鏈結出錯,於是搜尋引擎開始工作,搜到篇簡單的博文解釋,暫時做個標記吧 我們習慣是.h中放類的函式宣告,在.cpp中放類的函式定義,但在類模板中不能這樣做,如隨手寫了個demo測試了下 h中 cpp view plain copy pragma once tem...