【发布时间】:2019-07-24 04:14:10
【问题描述】:
谁能帮我找出这段代码中的问题。我正在使用代码块 17.12。 我正在尝试创建一个 Matrix 类,我想在其中使用构造函数初始化矩阵,然后使用函数获取数组的成员。 然后重载“*”运算符以将两个输入的矩阵相乘。然后重载 ostream 以将已经给定的矩阵显示为输入或乘积(如“cout
#include <iostream>
using namespace std;
class Matrix
{
private:
//static int row; //don't work
//static const int row; //don't work
//constexpr int row; //don't work
int row;
int column;
//Here my moto is to make a matrix which takes input from the user and
create the matrix of desired size at runtime.
double A[row][column];
public:
Matrix(int row,int column);
Matrix(Matrix &mat);
void setRowXColumn(int row,int column);
void setColumn(int column);
void setMatrix(Matrix A);
};
int main()
{
//Here 3 and 2 are the rows and columns of the matrix m respectively.
Matrix m(3,2);
return 0;
}
Matrix::Matrix(int row=0,int column=0)
{
setRowXColumn(int row,int column); //error: expected primary-expression before 'int'|
//what primary-expression?
}
Matrix::Matrix(Matrix &mat)
{
row=mat.row;
column=mat.column;
}
void Matrix::setRowXColumn(int row,int column)
{
if(row<0)
this->row=0;
else
this->row=row;
if(column<0)
this->column=0;
else
this->column=column;
}
//And i also want the members as input by the user at runtime.
void Matrix::setMatrix(Matrix A)
{
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
cout<<"Enter"<<Matrix A<<"["<<i<<"]"<<"["<<j<<"]"<<endl;
cin>>A[i][j];
}
}
}
从上面的代码我得到以下错误。
||=== 构建:在类矩阵中调试(编译器:GNU GCC 编译器)===|
类 Matrix\main.cpp|9|错误:无效使用非静态数据成员 'Matrix::row'|
类矩阵\main.cpp|7|注意:在此声明|
类 Matrix\main.cpp|9|错误:无效使用非静态数据成员 'Matrix::column'|
类矩阵\main.cpp|8|注意:在此声明|
类Matrix\main.cpp||在构造函数'Matrix::Matrix(int, int)':|
类矩阵\main.cpp|42|错误:'int'之前的预期主表达式|
类矩阵\main.cpp|42|错误:'int'之前的预期主表达式|
类Matrix\main.cpp||在成员函数'void Matrix::setMatrix(Matrix)':|中
Class Matrix\main.cpp|69|error: 'A' 之前的预期主表达式|
Class Matrix\main.cpp|70|error: no match for 'operator[]' (操作数类型是 'Matrix' 和 'int')|
||=== 构建失败:6 个错误,0 个警告(0 分钟,0 秒)===|
非常感谢您的帮助并感谢您。 我是一名正在学习 C++ 的学生。 我仍在处理此代码。
编辑:-到目前为止,我已经减少了错误,但是“双 A[row][column] 是我最头疼的问题。我想要这样,因为我想创建一个矩阵,就像我在主函数中所做的那样. 然后将数组的成员作为输入。 希望这次编辑能进一步澄清我的问题。
谢谢...
【问题讨论】:
-
double A[row][column];不合法。数组的大小必须在编译时知道。一些编译器允许你摆脱某些类型的可变长度数组,但不是这种用法。 -
这里是a link to a very simple, very robust matrix class,您可以将其用作起点或灵感。请注意它如何使用一维数组并执行索引数学以使其看起来像一个二维数组。
-
建议:编译测试前少写代码。如果你只写几行,最多写一个函数,你会更快地发现错误,并且它们没有太多机会建立起来。如果你让它们,虫子往往会联合起来攻击你。不要让他们。
-
这段代码有很多错误和误解。还有很多不同类型的错误。我知道你是一个初学者,但你现在已经过头了。忘记你得到的所有其他建议,user4581301 说的是最重要的事情。重新开始这个项目(我认为你到目前为止写的代码不值得保存)。一次编写几行代码,在编写更多代码之前编译和测试这些行并使其正常工作。这样,您一次只需要处理一个问题。
-
感谢您的回答。我目前正在研究你对我说的话,并试图从我的错误中吸取教训。我很快就会对我的代码进行编辑以使其正常工作。谢谢
标签: c++ matrix operator-overloading matrix-multiplication ostream