gpt4 book ai didi

c++ - 在没有参数列表的情况下无效使用模板名称 ‘Matrix’

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:38 25 4
gpt4 key购买 nike

这是我的 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;

}

这给出了以下内容

error: invalid use of template-name ‘Matrix’ without an argument list

我的代码有什么问题?

编辑:矩阵类定义为 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: error: default argument given for parameter 3 of ‘Matrix::Matrix(int, int, T)’ Matrix.h:16:3: error: after previous specification in ‘Matrix::Matrix(int, int, T)’

我的代码有什么问题?

最佳答案

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

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

此外,不要忘记在您使用此类的地方包含此 Cpp 文件。因为在模板的情况下,完整的正文应该对所有翻译单元可见。

编辑:在您编辑问题后,我注意到错误说明了一切。

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

关于c++ - 在没有参数列表的情况下无效使用模板名称 ‘Matrix’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7844198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com