1. 程式人生 > >C++中模板類宣告和實現能否分離?

C++中模板類宣告和實現能否分離?

1.宣告部分

//point.h

#ifndef _POINT_
#define _POINT_

template<class Elem> class Point
{
public:
    Point(Elem);
}
;
#endif

2.實現部分

//point.cpp

#include "point.h"
#include <iostream>
using namespace std;
template<class Elem> Point<Elem>::Point(Elem e)
{
    cout << e << endl;
}

3.主程式部分

//main.cpp

#include "point.h"     //出錯的地方
#include <iostream>
using namespace std;

void main()
{
    Point<int> p(10);
}

編譯的時候出現錯誤:

mainTest.obj : error LNK2019: 無法解析的外部符號 "public: __thiscall Point<int>::Point<int>(int)" (??0?$Point@H@@QAE@H@Z),該符號在函式 _main 中被引用
F:\C++Test\templateTest\Debug\templateTest.exe : fatal error LNK1120: 1 個無法解析的外部命令

4.解決辦法

將main.cpp中的#include "point.h" 修改為 #include "point.cpp"

5.總結

a)C++中模板的宣告和實現能分離,只是在主程式中#include的是相應的.cpp

b)C++中模板的宣告和實現最好不要分開,都寫在.h檔案,這是因為在多個cpp檔案中引用模板引數時可能引起重複定義的編譯錯誤