2011-02-06 82 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;指令,因为它会传播到它包含的所有文件。