【发布时间】:2015-12-14 19:59:25
【问题描述】:
我不明白返回临时对象有什么问题。如果我不使用析构函数,那么一切都很好。 但是使用析构函数会产生问题。多项式 1 和 2 的系数打印正确。多项式 3 也是。但是多项式 3 的 coeff[1] 和 coeff[2] 相加后没有给出正确的值。有人可以帮忙吗?
#include<iostream>
using namespace std;
class poly{
public:
float* coeff;
int degree;
int arr_size;
/*default constructor*/
poly(){
coeff = new float [11];
arr_size = 10;
for(int j=0;j<=arr_size;j++)
coeff[j] = 10;
cout << "Object created using default constructor..." << endl;
}
poly(poly &p){
arr_size = p.arr_size;
coeff = new float[arr_size+1];
for(int j=0;j<=arr_size;j++)
coeff[j] = p.coeff[j];
cout << "Copy constructor called......"<<endl;
}
~poly(){
if(coeff){
delete [] coeff;
coeff = NULL;
cout << "Destructor Msg:: Allocation free!!" << endl;
}
}
void show();
void setCoeff();
poly operator+ (poly);};
/*Show all coefficiens of a ploynomial*/
void poly :: show(){
for(int j=0; j<=arr_size; j++)
cout << "coeff[" << j <<"]:\t"<< coeff[j]<< endl;
}
/*To set a specific coefficient in the polynomial*/
void poly :: setCoeff(){
int i;
again: cout << "Enter degree of coefficient you want to set: ";
cin >> i;
if(i>arr_size || i<0){
cout << "!! Enter appropriate value." << endl;
goto again;
}
cout << "Enter new value: ";
cin >> coeff[i];
}
poly poly :: operator+ (poly p){
poly temp;
for(int i=0;i<=arr_size;i++)
temp.coeff[i] = coeff[i] + p.coeff[i];
return temp; //I think Problem in this line
}
int main(){
cout << "*********** WELCOME ***********" << endl;
poly p[3];
p[2] = p[0] + p[1];
p[2].show();
cout << "Thank You!!!" << endl;
return 0;
}
【问题讨论】:
-
您的问题陈述是“没有给出正确的值”。这不是一个好的问题陈述。
-
您只需阅读到
float* coeff;就可以猜出问题所在。使用std::vector<float>可以解决它。
标签: c++ object destructor