【发布时间】:2019-09-27 19:16:24
【问题描述】:
我在这段代码上停留了一段时间,无法编译,我到底做错了什么?如果编译时出现错误,请忽略它们,因为我可以自己修复。截至目前,我只是想让它运行。提前谢谢你。
#include <iostream>
#include <string.h>
//template <class t> class Matrix; //possible way of fixing the friend function.
using namespace std;
template<class T, size_t NROWS, size_t NCOLS>
std::ostream & operator<<(std::ostream &os, const Matrix<T,NROWS, NCOLS> &matrix);
template<class T, size_t NROWS = 1, size_t NCOLS = 1>
class Matrix{
public:
Matrix(){}
friend std::ostream &operator<< <>(std::ostream&os,const Matrix<T, NROWS, NCOLS> &matrix);
private:
T container[NROWS][NCOLS];
};
template<class T,size_t NROWS, size_t NCOLS>
std::ostream &operator<<(std::ostream &os,const Matrix<T,NROWS,NCOLS>&matrix){
for(size_t i=0;i<NROWS;++i){
for(size_t j=0;j<NCOLS;++j){
os <<matrix.container[i][j]<<" ";
}
os <<std::endl;
}
os <<std::endl;
}
int main(){
Matrix<float, 10, 5> mat;
cout << mat;
return 0;
}
我使用的IDE报错如下:
main.cpp:8:51:错误:没有名为“矩阵”的模板 std::ostream & 运算符
main.cpp:15:24: 错误:没有函数模板匹配函数模板特化'operator(std::ostream&os,const Matrix &matrix);
main.cpp:35:32:注意:在此处请求的模板类“矩阵”的实例化矩阵垫;
【问题讨论】:
-
FWIW,没有模板类或模板函数之类的东西。不过有类模板和函数模板。
-
您的代码包含标记为“可能的修复方式”的内容——为什么只有可能?你自己的答案有什么问题? (继续关注错误消息。你已经接近了。)