我试图减去两个矩阵并以这种格式打印它们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 ;
};
Run Code Online (Sandbox Code Playgroud)
这是子句的功能
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 ;
};
Run Code Online (Sandbox Code Playgroud)
<<需要将重载运算符的函数参数列表更改为
ostream& operator<< (ostream& out, const matrix& mat)
Run Code Online (Sandbox Code Playgroud)
请注意const.
否则匿名临时 (mat3 - mat1)无法绑定到重载.
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |