2014-11-20 77 views
0

我試圖使用模板,但它不工作,錯誤的是:「以前這裏聲明」,C++模板:

這是我的Matrix.h文件:

#ifndef MATRIX_H 
#define MATRIX_H 

template <class T> 
class Matrix 
{ 
public: 
    Matrix(int); // default cunstractor 

private: 
    int rows, columns; 
}; 

#include "Matrix.cpp" 
#endif 

這是我Matrix.cpp文件

#include "Matrix.h" 
#include<iostream> 
using namespace std; 

template <class T> 
Matrix<T>::Matrix(int a) // Default constructor 
{ 
    columns = a; 
    rows = 0; 
} 

,這是主要的文件:

#include<iostream> 
#include "Matrix.h" 
using namespace std; 

int main() 
{ 

Matrix<int> m1(5); 
return 0; 
} 

我知道代碼看起來非常愚蠢和簡單,但我寫了更多,我把它減少到這樣非常簡單的代碼,並再次不起作用。即使我刪除

#include "Matrix.cpp" 

裏面的Matrix.h文件,但仍然有問題。

+0

'#include「Matrix.cpp」'在Matrix.h中。你應該被通知.cpps永遠不會,EVER,E V E R!包括 – Creris 2014-11-20 18:26:10

+0

這不是關於那個話題......這是關於一個錯誤,這對我來說並不意味着什麼... – MoHo 2014-11-20 18:27:32

+0

模板定義*必須*在標題中。看到[這個問題](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Barry 2014-11-20 18:29:56

回答

1

將matrix.cpp文件的內容(模板定義)移動到matrix.h。

+0

我知道我可以做到這一點,但這不是解決方案 – MoHo 2014-11-20 18:39:10

+0

http://www.parashift.com/c++-faq-lite/templates-defn-vs-decl.html http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – learningToCode 2014-11-20 18:41:38

+1

@ user1796381:這是解決方案。如果你真的想要做你的頭文件中包含源文件的奇怪的詭計,那麼請不要在源文件中包含頭文件。但嚴重:只需在標題中定義模板。 – 2014-11-20 19:02:02