【发布时间】:2018-09-27 20:19:01
【问题描述】:
我在大学学习 OOP 课程,我们应该重载 +、-、*、+=、-= 和其他一些运算符来处理矩阵运算,只使用结构和运算符重载。我想出了那个代码,用户输入一个一维数组,然后这个数组变成一个二维数组 或 矩阵。
函数createMatrix 将采用一维数组,然后定义行 和列 的数量,然后将该数组中的值放入matrix 结构或者在结构中的一个元素中是具体的。然后我定义了+、-和
它还没有完成,但是程序没有输出任何东西,我找不到错误在哪里,是在“+”运算符还是“
#include <iostream>
#include <algorithm>
using namespace std;
struct matrix{
int* data; //since it is a 1d array which will later be stored in the matrix
int row, col;
};
void createMatrix(int row, int col, int num[], matrix& mat); //by reference so that I fetch it by address from memory
matrix operator+ (matrix mat1, matrix mat2){ //Addition
matrix mat;
for(int i = 0; i < max(mat1.row*mat1.col, mat2.row*mat2.col); i++){
mat.data[i] = mat1.data[i] + mat2.data[i];
}
return mat;
}
matrix operator- (matrix mat1, matrix mat2){ //Subtraction
matrix mat;
for(int i = 0;i < max(mat1.row*mat1.col, mat2.row*mat2.col); i++){
mat.row = mat1.row - mat2.row;
}
return mat;
}
ostream operator<< (ostream& out, matrix mat){
for(int i = 0; i < ((mat.row)*(mat.col)); i++){
if(i % mat.row == 0 ){
cout<<endl;
}
else{out<<mat.data[i]<<" ";}
}
}
int main()
{
int row1, col1;
int row2, col2;
cout<<"Enter Rows of first matrix: "; cin>>row1;
cout<<"Enter Cols of first matrix: "; cin>>col1;
cout<<"Enter Rows of second matrix: "; cin>>row2;
cout<<"Enter Cols of second matrix: "; cin>>col2;
int arr1[row1*col1], arr2[row2*col2];
cout<<"Enter the values you which to add in the first matrix: ";
for(int i = 0; i < row1*col1; i++){
cin>>arr1[i];
}
cout<<"Enter the values you which to add in the second matrix: ";
for(int i = 0; i < row2*col2; i++){
cin>>arr2[i];
}
matrix mat1, mat2, mat3;
createMatrix(row1, col1, arr1, mat1);
createMatrix(row2, col2, arr2, mat2);
mat3 = mat1 + mat2;
cout<<mat3;
return 0;
}
void createMatrix(int row, int col, int num[], matrix& mat){
mat.row = row;
mat.col = col;
mat.data = new int [col * row]; //We are trying to make a matrix from a 1d array, so we will stretch the matrix -which is a 2d array
for(int i = 0; i < col * row; i++){ //in 1-D of size row *col
mat.data[i] = num[i]; //Depending on the parameter the data array will be filled dynamically
}
}
【问题讨论】:
-
可能相关也可能不相关(不知道您要查找的错误是什么):编译器可能试图警告您
operator<<缺少return语句。 -
int arr1[row1*col1], arr2[row2*col2];定义可变长度数组 (VLA)。 VLA 不是标准 C++。您的编译器可能支持也可能不支持这种行为,如果支持,这是一种非常容易导致堆栈溢出的方法。如果你改用std::vector可能是最好的。 -
createMatrix看起来应该返回matrix,而不是将其作为参数。要让它发挥作用(因为不这样做就无法编写有价值的 C++ 代码),请熟悉 Rules of Three, Five, and Zero。
标签: c++ arrays matrix operator-overloading