我試圖使用模板,但它不工作,錯誤的是:「以前這裏聲明」,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文件,但仍然有問題。
'#include「Matrix.cpp」'在Matrix.h中。你應該被通知.cpps永遠不會,EVER,E V E R!包括 – Creris 2014-11-20 18:26:10
這不是關於那個話題......這是關於一個錯誤,這對我來說並不意味着什麼... – MoHo 2014-11-20 18:27:32
模板定義*必須*在標題中。看到[這個問題](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Barry 2014-11-20 18:29:56