C 類模板分檔案

2021-10-03 17:40:37 字數 796 閱讀 8269

問題:類模板的成員函式是在呼叫時才被建立,導致分檔案編寫時呼叫不到。

解決:1.直接包含cpp檔案

2.將宣告和實現寫到同乙個檔案中,並更該字尾名為.hpp,.hpp是約定的名字,並不是強制

標頭檔案:person.hpp

#include

using

namespace std;

template

<

classt1,

class

t2>

class

person

;template

<

classt1,

class

t2>

person

::person

(t1 name, t2 age)

//對於成員函式,需要指明類的引數的代表

template

<

classt1,

class

t2>

void person

::show()

原始檔:test.cpp

//第二種方式,將.h和.cpp中的內容寫到一起,將字尾名改為.hpp

#include

"person.hpp"

void

test()

intmain()

將類模板的宣告和實現都放在.hpp中,並在cpp檔案中進行引用即可。

類模板分檔案編寫

示例 person.hpp中 pragma once include using namespace std include templateclass person 建構函式 類外實現 templateperson person t1 name,t2 age 成員函式 類外實現 templatev...

C 模板類的分檔案編寫問題及解決

pragma once include include using namespace std templateclass person include pch.h include person.h templateperson person t1 name t2 age templatevoid ...

c 類模板之分檔案編寫問題及解決

我們在實際專案中一般習慣標頭檔案 h 和原始檔 cpp 分開寫,這樣做的好處良多,但是如果遇到了類模板,這樣可能會有一點兒問題。我們通過乙個例子來看 person.h 1 pragma once 2 include 3 include4 using namespace std 56 template...