析构函数,返回临时对象

Destructor , Returning temp object

我不明白返回临时对象有什么问题。如果我不使用析构函数那么一切都很好。 但是对于析构函数,它会为多项式 1 和 2 创建 problem.coefficients 并打印 correctly.polynomial 3。但是多项式 3 的加法 coeff[1] 和 coeff[2] 没有给出正确的 value.Can 有人帮忙吗?

#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;
}

您没有定义赋值运算符,所以当您定义 p[2] = p[0] + p[1] 时,将使用默认赋值运算符,它将 p[2].coeff 指定为指向与 coeff 相同的数组添加创建的临时对象。

所以当临时对象被销毁时,它的析构函数会删除数组,p[2].coeff现在是一个无效指针。因此访问它会导致未定义的行为。

复制构造函数也应将 const 引用作为其参数。

如果在 class 多边形中使用 "bool temp" 会怎样?

poly poly :: operator+ (poly p){
poly* buffer = new poly();
buffer->temp = true;
for(int i=0;i<=arr_size;i++)
    temp.coeff[i] = coeff[i] + p.coeff[i];
if (p.temp == true)
    delete &p;
return buffer;
}