c++ - 为什么我在编译模板类时遇到问题?
问题描述
我已经在这段代码上停留了一段时间,无法编译,我到底做错了什么?如果编译时出现错误,请忽略它们,因为我可以自己修复。截至目前,我只是想让它运行。先感谢您。
#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: 错误:没有名为 'Matrix' 的模板 std::ostream & operator<<(std::ostream &os, const Matrix &matrix);
main.cpp:15:24: 错误:没有函数模板匹配函数模板特化 'operator<<' 朋友 std::ostream &operator<< <>(std::ostream&os,const Matrix &matrix);
main.cpp:35:32:注意:在此处请求的模板类“矩阵”的实例化矩阵垫;
解决方案
如果您取消注释第 4 行,并按如下方式更改,您的代码将编译:
template <class t, size_t, size_t> class Matrix; //possible way of fixing the friend function.
您的问题似乎是前向声明的 Matrix 模板参数与稍后出现的 Matrix 定义不匹配。
此外,虽然代码将在此修复后编译,但仍有一个警告,您可能还想修复:
In function 'std::ostream& operator<<(std::ostream&, const Matrix<T, NROWS, NCOLS>&)':
31:1: warning: no return statement in function returning non-void [-Wreturn-type]
推荐阅读
- ios - ITMS-90078:缺少推送通知权利 - 您的应用似乎注册了 Apple 推送通知服务
- react-native - Flutter 的小部件不是真正自适应的意思
- bash - 用于汇总文件中相似文本行的数字的 Shell 命令
- vue.js - 如何使用 bootstrap-vue b-table 在单行中开始新行
- java - 如何获取放置在 java 项目文件夹中的本地文件夹的 url
- java - 从 neo4j 返回 NodeEntity 不包含关系或连接节点
- java - Java - 向 Slack Webhook 发送消息
- ios - 在 iOS swift/Objective C 中实现 Diffie Hellman 生成公钥和私钥的方法是什么?(除了 Chilkat)
- python - 如何获得大于10000的电报组的成员
- r - 动态选择数据框