使用C+的简单矩阵示例+;模板类 我试图用C++模板编写一个平凡的矩阵类,试图修复我的C++,并向同伴编码器解释一些东西。

使用C+的简单矩阵示例+;模板类 我试图用C++模板编写一个平凡的矩阵类,试图修复我的C++,并向同伴编码器解释一些东西。,c++,templates,C++,Templates,这就是我到目前为止得到的: template class<T> class Matrix { public: Matrix(const unsigned int rows, const unsigned int cols); Matrix(const Matrix& m); Matrix& operator=(const Matrix& m); ~Matrix(); unsigned int getNumRows()

这就是我到目前为止得到的:

template class<T>
class Matrix
{
public:
    Matrix(const unsigned int rows, const unsigned int cols);
    Matrix(const Matrix& m);
    Matrix& operator=(const Matrix& m);
    ~Matrix();

    unsigned int getNumRows() const;
    unsigned int getNumCols() const;

    template <class T> T getCellValue(unsigned int row, unsigned col) const;
    template <class T> void setCellValue(unsigned int row, unsigned col, T value) const;

private:
    // Note: intentionally NOT using smart pointers here ...
    T * m_values;
};


template<class T> inline T Matrix::getCellValue(unsigned int row, unsigned col) const
{
}

template<class T> inline void Matrix::setCellValue(unsigned int row, unsigned col, T value)
{
}
模板类
类矩阵
{
公众:
矩阵(常量无符号整数行,常量无符号整数列);
矩阵(常数矩阵&m);
矩阵和运算符=(常数矩阵和m);
~Matrix();
unsigned int getNumRows()常量;
unsigned int getNumCols()常量;
模板T getCellValue(无符号整数行,无符号列)常量;
模板void setCellValue(无符号整行、无符号列、T值)常量;
私人:
//注意:这里有意不使用智能指针。。。
T*m_值;
};
模板内联T矩阵::getCellValue(无符号整数行,无符号列)常量
{
}
模板内联void矩阵::setCellValue(无符号整数行、无符号列、T值)
{
}
我被困在ctor上,因为我需要分配一个新的[]T,它似乎需要一个模板方法——但是,我不确定我以前是否遇到过模板化的ctor


如何实现ctor?

您可以在构造函数中访问
T
,因此构造函数本身不需要是模板。例如:

Matrix::Matrix(const unsigned int rows, const unsigned int cols)
{
    m_values = new T[rows * columns];
}
考虑对数组使用智能指针,如
boost::scoped_array
std::vector
,以使资源管理更容易一些

如果矩阵的大小固定,另一种选择是将行和列与T一起作为模板参数:

template <class T, unsigned Rows, unsigned Columns>
class Matrix 
{ 
    T m_values[Rows * Columns];
};
模板
类矩阵
{ 
T m_值[行*列];
};
最大的优点是大小是矩阵类型的一部分,这有助于在编译时强制执行规则,例如,在执行矩阵乘法时确保两个矩阵的大小兼容。它也不需要动态分配阵列,这使得资源管理更容易一些


最大的缺点是您无法更改矩阵的大小,因此它可能无法满足您的需要。

@james:谢谢您的快速响应。我更喜欢第一种方法(尽管我可以看到另一种方法的吸引力)。最后一个问题(使用第一种方法)-您确定ctor可以访问T(我以前从未见过)。另外,它是一个模板函数(签名表明它不是)。所以(假设它不是一个方法模板,那么我可以在我的源文件(而不是头文件)中实现它吗)?@skyeagle:您可以在类模板定义内的任何位置使用
T
。构造函数不是模板,但由于它是类模板的成员函数,因此必须在标题中实现。MSDN有一个类模板成员函数的很好示例:非常重要--您需要使用
作用域数组
如果您使用
new[]
。另外,我建议使用
vector
而不是数组。@rlbond:scoped_数组很好理解。@Oops!@james应该将这个向量定义为Matrix::Matrix()?不要忘记使用复选标记接受前面问题的答案。请参阅“我如何在这里提问”的常见问题解答有关更多详细信息,请参见。您对
getCellValue
setCellValue
的声明不正确--您不需要(也不可能有)
模板放在它们前面。此外,当您想在类外定义它们时,它需要读取
template inline t Matrix::getCellValue(unsigned int row,unsigned col)康斯特:谢谢你指出了这个问题。我想我的C++比我想象的更生锈了…