C++ 功能过载>&燃气轮机;输入矩阵(类)的步骤为';行不通
因此,我编写了这个类,它看起来有点像这样:C++ 功能过载>&燃气轮机;输入矩阵(类)的步骤为';行不通,c++,class,oop,operator-overloading,istream,C++,Class,Oop,Operator Overloading,Istream,因此,我编写了这个类,它看起来有点像这样: class matrix { // Friends friend ostream & operator << (ostream &os, const matrix &mat); friend istream & operator >> (istream &is, matrix &mat); private: double *mdat
class matrix
{
// Friends
friend ostream & operator << (ostream &os, const matrix &mat);
friend istream & operator >> (istream &is, matrix &mat);
private:
double *mdata;
int rows, columns, size;
你知道我做错了什么吗?完整代码
编辑:
忘了说,我包括赋值运算符,因为它有相同(或类似)的问题。您从未在
运算符>>
重载中更新mat.size
,因此尽管您在中读取了4个值,但矩阵认为它是空的,并且没有输出任何内容
同样,非常重要的是,如果传递给操作符>>
重载的矩阵已经有数据,那么您将泄漏内存,因为您没有释放该数据,并且您将一个新指针分配给mat.mdata
您可以这样做:
istream & operator >> (istream &is, matrix &mat) {
int rows, columns;
is >> rows >> columns;
if (!is)
return is; // couldn't read rows and cols
matrix tmp(rows, columns);
if(tmp.size>0) {
cout << "Enter " << tmp.size << " values (top row, second row... last row - left to right)" << endl;
这需要一个正确的matrix::swap(matrix&)
成员函数,由于许多原因,该函数非常有用
return is;
}
注意,我进行了错误检查,以确保您确实从流中读取了预期的数据
赋值运算符中的错误如下所示:
int size=0;
// Now copy size and declare new array
size=m.getcols()*m.getrows();
声明一个名为size
的新局部变量,并更新该变量。这意味着,此->大小
永远不会更新。您不想声明新的大小
,只想更新成员变量,因此将上述更改为:
// Now copy size and declare new array
size=m.getcols()*m.getrows();
谢谢你的详细回答,我今晚晚些时候回到电脑前会检查它,看看它是否能解决我的问题,然后将它标记为接受:)哦,是的,我忘了我甚至在矩阵中包含了一个大小变量。
istream & operator >> (istream &is, matrix &mat) {
int rows, columns;
is >> rows >> columns;
if (!is)
return is; // couldn't read rows and cols
matrix tmp(rows, columns);
if(tmp.size>0) {
cout << "Enter " << tmp.size << " values (top row, second row... last row - left to right)" << endl;
// Copy values into new array
for(int i=0;i<tmp.size;i++) {
is >> tmp.mdata[i];
}
}
if (is) // read all values successfully
mat = tmp;
mat.swap(tmp);
return is;
}
int size=0;
// Now copy size and declare new array
size=m.getcols()*m.getrows();
// Now copy size and declare new array
size=m.getcols()*m.getrows();