重载运算符 (<<) cout 在 c ++ 中不起作用,当我互相减去两个矩阵时不起作用
overloading operator (<<) cout in c++ is not working when i Subtract two matrix from each other
我正在尝试减去两个矩阵并以这种格式打印它们 库特 <<(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)
无法绑定到重载。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- 我已经完成了<<运算符重载,但它'It’不起作用