没有参数列表的模板名称'Matrix'的使用无效

时间:2011-10-21 01:52:51

标签: c++ templates compiler-errors

这是我的Matrix.cpp文件。 (有一个单独的Matrix.h文件)

#include <iostream>
#include <stdexcept>

#include "Matrix.h"

using namespace std;

Matrix::Matrix<T>(int r, int c, T fill = 1)
{
  if (r > maxLength || c > maxLength) {
    cerr << "Number of rows and columns should not exceed " << maxLen << endl;
    throw 1;
  }

  if (r < 0 || c < 0) {
    cerr << "The values for the number of rows and columns should be positive" << endl;
    throw 2;
  }

  rows = r;
  cols = c;

  for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
      mat[i][j] = fill;

}

这给出了以下

  

错误:无法使用没有参数列表的模板名称'Matrix'

我的代码中出现了什么问题?

编辑:Matrix类定义为template<class T>

编辑: 这是我的Matrix.h文件:

#include <iostream>
#include <math.h>

#define maxLength 10;

using namespace std;

template <class T>

class Matrix
{
public:
    Matrix(int r, int c, T fill = 1);

private:
    int rows, cols;
        T mat[10][10];
};

这是Matrix.cpp文件:

#include <iostream>
#include <stdexcept>

#include "Matrix.h"

using namespace std;

template<class T>
Matrix<T>::Matrix(int r, int c, T fill = 1)
{
}

这会出现以下错误:

  

Matrix.cpp:12:43:错误:给出参数3的默认参数   'Matrix :: Matrix(int,int,T)'Matrix.h:16:3:错误:之前的   'Matrix :: Matrix(int,int,T)'中的规范

我的代码有什么问题?

2 个答案:

答案 0 :(得分:15)

如果你的班级是模板,那么正确的定义应该是,

template<class T>
Matrix<T>::Matrix(int r, int c, T fill)  // don't give default argument
...

此外,不要忘记在您使用此类的地方包含此Cpp文件。因为在模板的情况下,所有翻译单元都应该可以看到全身。

修改:在您编辑过的问题之后,我发现错误说明了这一切。

您不应该在方法定义中提供默认参数。在声明(你已经给出)中给出是足够的。如上所示制定template定义,错误将消失。

答案 1 :(得分:3)

你应该写为:

template<class T>
Matrix<T>::Matrix(int r, int c, T fill = 1)
{
  ..
}

是的,这很乏味。这可能不是一个好主意 源文件中的模板定义,请参阅 http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

所以最简单的方法是放置模板成员的定义 在头文件中的类模板定义内。