c++ - 当我将两个矩阵相减时,C++ 中的重载运算符 (<<) cout 不起作用
问题描述
我正在尝试减去两个矩阵并以这种格式打印它们 cout << (mat1 - mat2 ) << endl ; 但是 cout 不工作,当我打印一个矩阵时它工作,这是我不认为我应该为此创建另一个 cout 运算符的代码
#include <iostream>
#include <iomanip>
using namespace std;
struct matrix {
int** data;
int row, col;
};
void createMatrix (int row, int col, int num[], matrix& mat) {
mat.row = row;
mat.col = col;
mat.data = new int* [row];
for (int i = 0; i < row; i++)
mat.data[i] = new int [col];
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
mat.data[i][j] = num[i * col + j];
} ;
ostream& operator<< (ostream& out , matrix& mat ) {
for (int i =0 ; i< mat.row ; i++) {
for (int j =0 ; j < mat.col ; j++) {
out << mat.data [i] [j] << " " ;
}
cout << endl ;
}
return out ;
};
这是减法的功能
matrix operator- (matrix mat1, matrix mat2) {
matrix mattt ;
if (mat1.row == mat2.row && mat1.col == mat2.col) {
for (int i =0 ; i< mat1.row ; i++) {
for (int j =0 ; j < mat1.col ; j++) {
mattt.data[i][j] = ((mat1.data [i][j]) - (mat2.data [i][j])) ;
}
}
}
else {
cout << " the matrixs dont have the same dimensions " << endl ;
}
return mattt ;
};
int main() {
int data1 [] = {1,2,3,4,5,6,7,8};
int data2 [] = {13,233,3,4,5,6};
int data3 [] = {10,100,10,100,10,100,10,100};
matrix mat1, mat2, mat3;
createMatrix (4, 2, data1, mat1);
createMatrix (2, 3, data2, mat2);
createMatrix (4, 2, data3, mat3);
cout << mat1 << endl;
cout << mat2 << endl;
cout << mat3 << endl;
cout << ( mat3 - mat1 ) << endl ;
};
解决方案
重载运算符的函数参数列表<<
需要更改为
ostream& operator<< (ostream& out, const matrix& mat)
请注意const
.
否则匿名临时 (mat3 - mat1)
不能绑定到重载。
推荐阅读
- c - 如何使用 Oracle Solaris 10 1/13 s10s_u11wos_24a SPARC 在 C 中编译此程序
- integer-programming - 整数规划:是否可以定义不兼容约束?
- c# - 如何使用 SSIS 将文件上传到 S3?
- amazon-cloudformation - 在创建 Sagemaker 笔记本实例时关联 CodeCommit 存储库
- salesforce - 对于自定义对象,有没有办法将 SFDX 文件结构转换/映射为单个 .object 文件?
- javascript - 如何使用 javascript 数组和按钮将响应放入 html 表单中以在表单字段中获取响应
- javascript - 什么是 ES6 类的优雅混合/组合语法?
- openvas - 使用带有过滤器的 omp xml 命令从 openvas 获取单个报告
- python - 如何在 Python 中基于现有列创建新列
- powershell - 将对象从一个脚本传递到另一个