tha*_*era 5 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;
}
Run Code Online (Sandbox Code Playgroud)
这给出了以下内容
错误:无法使用没有参数列表的模板名称"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];
};
Run Code Online (Sandbox Code Playgroud)
这是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)
{
}
Run Code Online (Sandbox Code Playgroud)
这会出现以下错误:
Matrix.cpp:12:43:错误:为'Matrix :: Matrix(int,int,T)的参数3给出的默认参数'Matrix.h:16:3:错误:在'Matrix :: Matrix(之前的规范)之后int,int,T)'
我的代码有什么问题?
iam*_*ind 15
如果你的类是模板,那么正确的定义应该是,
template<class T>
Matrix<T>::Matrix(int r, int c, T fill) // don't give default argument
...
Run Code Online (Sandbox Code Playgroud)
另外,不要忘记在您使用此类的地方包含此Cpp文件.因为在模板的情况下,所有翻译单元都应该可以看到全身.
编辑:在您编辑的问题之后,我注意到错误说明了一切.
您不应该在方法定义中给出默认参数.在声明(你已经给出)中给出是足够的.让你的template定义如上图所示与误差应消失.
| 归档时间: |
|
| 查看次数: |
23642 次 |
| 最近记录: |