首页 > 解决方案 > 正确的模板声明和实现

问题描述

我正在尝试声明模板声明以在 C++ 中实现二维矩阵。我以前从未使用过模板,我被要求使用它们。我只需要正确的声明语法帮助,因为友元函数和模板的重载令人困惑,并且存在不同的问题,至少与我习惯的相比。

内部文档像往常一样毫无用处。我最专注于找出重载运算符的错误,老实说,它让我困惑了至少一整天。

class Matrix
{
      public:
      Matrix(int sizeX, int sizeY, T initValue = T());


      T &operator()(int x, int y);

     template <class Type>
     friend ostream &operator<<(ostream &out, const Matrix<type> &m);

      template <class Mtype>
     friend Matrix<Mtype> operator+(const Matrix<MType> &m1, const Matrix<Mtype>& m2);

    private:
   vector< vector<T> > data;
   int dx, dy;
}
#ifndef MATRIX_CPP
Template <class T>
Matrix<T>::Matrix(int sizeX, int sizeY, T initValue){
dx = sizeX;
dy = sizeY;
initvalue = T(sizeX, sizeY);
}

T& operator()(int x, int y){
return T[x][y];
}

错误类型名'T'没有命名类型

'Matrix::Matrix(int int, T)' 的无效重新定义

标签: c++classtemplates

解决方案


您缺少模板类型 T。

template <class T>
 class Matrix
{
public:

     Matrix(int sizeX, int sizeY, T initValue = T());
...

请注意,模板代码实现应该在头文件中,而不是在 cpp 中。


推荐阅读