C++模板類不支持分離編譯

模板類不支持分離編譯。你須要把全部的申明和定義放在一個文件裏實現。 spa

舉個例子,cpp_1.h以下: 編譯器

template<class numtype> 編譯

class cpp_1 { 模板

    public: class

            numtype a;
方法

            cpp_1(numtype);
文件

} co

cpp.cpp以下: background

#include "cpp_1.h" 生成

template<class numtype>

cpp_1<class numtype>::cpp_1(numtype x){

    a = x;

}

main.cpp以下:

#include "cpp.h"

int main(){

    cpp_1<int> s(3); //第三行

    return 0;

}


由於模板類不支持分離編譯。上面第三行就會報錯,編譯器在編譯cpp的時候不知道要生成cpp_1<int>::cpp_1(int)的代碼,因此link的時候就找不到.

所以,正確的方法是,把模板類的聲明和實現放在一個文件裏。

相關文章
相關標籤/搜索