【发布时间】:2020-08-08 09:50:30
【问题描述】:
我似乎无法通过函数或其他方式访问类变量,在我重载的
我正在编写一个使用重载运算符执行各种矩阵函数的程序。现在我正在尝试使函数与大小不是 3x3 的矩阵一起工作,并且这些函数更早地与全局变量 s 一起工作,但我希望在 << 和 >> 之前重新定义 rows调用。
#include <iostream>
using namespace std;
#define s 3
class Matrix
{
private:
public:
int rows,cols;
int rows1, rows2, cols1, cols2;
int **m;
void setRows(int rowsa);
int getRows();
Matrix()
{
m = new int *[10];
for (int i = 0; i < 10; i++)
{
m[i] = new int[10];
}
}
friend Matrix operator+(Matrix &m1, Matrix &m2);
friend Matrix operator-(Matrix &m1, Matrix &m2);
friend Matrix operator*(Matrix &m1, Matrix &m2);
friend ostream &operator<<(ostream &os, Matrix &m1);
friend istream &operator>>(istream &is, Matrix &m1);
};
Matrix operator+(Matrix &m1, Matrix &m2)
{
Matrix m3 = Matrix();
for (int i = 0; i < s; i++)
{
for (int j = 0; j < s; j++)
m3.m[i][j] = m1.m[i][j] + m2.m[i][j];
}
return m3;
}
Matrix operator-(Matrix &m1, Matrix &m2)
{
Matrix m3 = Matrix();
for (int i = 0; i < s; i++)
{
for (int j = 0; j < s; j++)
m3.m[i][j] = m1.m[i][j] - m2.m[i][j];
}
return m3;
}
Matrix operator*(Matrix &m1, Matrix &m2)
{
Matrix m3 = Matrix();
Matrix rix;
for (int i = 0; i < rix.rows1; i++)
{
for (int j = 0; j < rix.cols2; j++)
{
for (int k = 0; k < rix.cols1; k++)
{
m3.m[i][j] = m1.m[i][k] * m2.m[k][j];
}
}
}
return m3;
}
ostream &operator<<(ostream &os, Matrix &m)
{
Matrix rix;
for (int i = 0; i < rix.rows; i++)
{
for (int j = 0; j < rix.cols; j++)
os << m.m[i][j] << " ";
os << "\n";
}
return os;
}
istream &operator>>(istream &is, Matrix &m1)
{
//overloaded >> to input the values of a matrix
// PROBLEM IS HERE
Matrix rix;
cout<<"value of rows1"<<rix.rows1<<endl;
cout<<"value of rows"<<rix.rows<<endl;
cout<<"value of getRows"<<rix.getRows()<<endl;
int k;
for (int i = 0; i < rix.rows; i++)
{
for (int j = 0; j < rix.cols; j++)
{
cout << "Enter element "
<< "(" << i << "," << j << "): ";
cin >> k;
m1.m[i][j] = k;
}
}
}
void Matrix::setRows(int rowsa){
rows= rowsa;
}
int Matrix::getRows(){
return rows;
}
int main()
{
int rosx;
Matrix m1 = Matrix();
Matrix m2 = Matrix();
Matrix rix;
cout << "Number of rows for the first Matrix? (max 10)" << endl;
cin >> rix.rows1;
cout << "Number of columns for the first Matrix? (max 10)" << endl;
cin >> rix.cols1;
cout << "Number of rows for the second Matrix? (max 10)" << endl;
cin >> rix.rows2;
cout << "Number of columns for the second Matrix? (max 10)" << endl;
cin >> rix.cols2;
cout << "input the elements of the first matrix: " << endl;
rix.setRows(rix.rows1);
cout <<rix.rows;
cin >> m1;
cout << m1;
cout << "input the elements of the second matrix: " << endl;
rix.rows = rix.rows2;
rix.cols = rix.cols2;
cin >> m2;
cout << m2;
Matrix m3 = m1 * m2;
cout << "output" << endl;
cout << m3;
return 0;
}
【问题讨论】:
-
您似乎对在输入和输出函数开始时声明新矩阵感到困惑。在您的输入中,您有一个非常好的矩阵
m1。它的行和列没有设置任何东西,所以迭代它们没有意义,但这就是你应该使用的矩阵。
标签: c++ class matrix operator-overloading istream