【发布时间】:2021-10-07 19:29:31
【问题描述】:
函数调用下面的语句没有被执行。我很茫然,为什么会这样?有人可以澄清一下。请考虑下面的代码:
#include<iostream>
#include<cmath>
using namespace std;
class Matrix
{
private:
int row,col;
double *values;
public:
Matrix();
Matrix(int r, int c, double* x);
void setdim(int m, int n){row=m;col=n;}
int getrowdim() const {return row;}
int getcoldim() const {return col;}
void set_values(int i, double x);
double get_value(int i) const;
friend Matrix operator+(const Matrix &A, const Matrix &B);
};
Matrix::Matrix()
{
this->row = 0;
this->col = 0;
this->values = NULL;
}
Matrix::Matrix(int r, int c, double* x)
{
this->row = r;
this->col = c;
this->values = new double[r*c];
for (int i =0;i<r*c;i++)
{
cout<<"Enter value ["<<i<<"] ";
cin>>this->values[i];
}
}
void Matrix::set_values(int k, double x)
{
this->values[k] = x;
}
Matrix operator+(const Matrix &A, const Matrix &B)
{
int rowa = A.getrowdim();
int cola = A.getcoldim();
int rowb = B.getrowdim();
int colb = B.getcoldim();
if(rowa == rowb && cola == colb)
{
Matrix C;
C.setdim(rowa, colb);
for(int i =0; i< rowa*cola ; i++)
{
cout<<"i = "<<i<<", A.get_value = "<<A.get_value(i)<<", B.get_value = "<<B.get_value(i)<<endl;
double m = A.get_value(i) + B.get_value(i);
cout<<m<<endl;
C.set_values(i, m );
cout<<"Returned from C.set_values()"<<endl;
// THIS STATEMENT DOES NOT GET PRINTED. PLEASE TELL THE REASON // WHY. I SUSPECT THE ERROR IS HERE
}
return C;
}
else
{
cout<<"Invalid Operation";
return A;
}
}
double Matrix::get_value(int i) const
{
return this->values[i];
}
int main()
{
Matrix A(2,2,NULL);
Matrix B(2,2,NULL);
Matrix C;
C = A+B;
return 0;
}
语句 - 从 C.set_values() 返回的语句根本不会被打印出来。
有人可以帮助澄清为什么会这样吗?非常感谢您的帮助!
【问题讨论】:
-
不要使用原始的拥有指针作为成员。如果你这样做,你需要正确管理它。您的代码中还有更多问题。使用
std::vector<double> values;作为成员将解决其中的大部分问题 -
您是否使用调试器单步执行函数以确定发生了什么?
-
setdim设置了row和col,但您仍然没有为coeff分配任何内存。 -
@MathMan 默认构造函数将指针设置为
NULL,但所有其他方法都希望它指向一个数组。那不仅“不好”,而且完全错误。更一般地说:类不遵守 3/5 规则,当类管理资源时这是强制性的 -
@MathMan 初学者经常想练习“手动方式”,但不幸的是,当一个人不了解 3/5 规则时,很容易出错。这有点像你第一次游泳时尝试穿越海洋(实际上你可以乘坐摩托艇;)
标签: c++ friend-function