2011-02-06 81 views
0

嗨 我在C++學習模板,所以我決定寫一個模板類的矩陣類。在Matrix.h文件我寫C++模板 - 矩陣類

#pragma once 
#include "stdafx.h" 
#include <vector> 



using namespace std; 

template<class T> 
class Matrix 
{ 
public: 

    Matrix(); 

    ~Matrix(); 
    GetDataVector(); 
    SetDataVector(vector<vector<T>> dataVector); 
    bool operator == (Matrix* matrix); 
    bool operator < (Matrix* matrix); 
    bool operator <= (Matrix* matrix); 
    bool operator > (Matrix* matrix); 
    bool operator >= (Matrix* matrix); 
    Matrix* operator + (Matrix* matrix); 
    Matrix* operator - (Matrix* matrix); 
    Matrix* operator * (Matrix* matrix); 

private: 
    vector<vector<T>> datavector; 
    int columns,rows; 


}; 

矩陣CPP視覺Stuio程序自動生成的代碼默認構造

#include "StdAfx.h" 
#include "Matrix.h" 


Matrix::Matrix() 
{ 
} 



Matrix::~Matrix() 
{ 
} 

但是如果我想編譯這個我得到一個錯誤

「矩陣':使用類模板 需要模板參數列表 錯誤在默認構造函數中的文件Matrix.cpp中 可能是什麼問題?

+1

你想`布爾運算符==(常量矩陣&矩陣)const;`而不是`bool運算符==(矩陣*矩陣);`。另外,不需要析構函數,因爲std :: vector會自行清理。 – fredoverflow 2011-02-06 15:24:57

+0

您還可以查看犰狳(http://arma.sourceforge.net/download.html)的源代碼。來源很清楚,圖書館很棒。順便說一句,它是唯一積極維護的像樣的C++線性代數庫。 – 2011-02-06 15:55:21

回答

4

你必須寫類的函數實現瞭如:

template <typename T> 
Matrix<T>::Matrix() {} 

template <typename T> 
Matrix<T>::~Matrix() { } 
+7

然後將實現放在標題中。 – robert 2011-02-06 15:23:27

1

您不能將模板類或方法的定義放到其他文件中,因爲鏈接器不會鏈接它(理論上export存在,但沒有編譯器實現它)。你可以把它放到其他文件,然後將它包含模板聲明後:

template<class T> 
class Matrix 
{ 
// (...) methods declarations here 
}; 

#include "matrix_implementation.hpp" 

也不要使用頭文件using namespace std;指令,因爲它會傳播到它包含的所有文件。