我不明白返回临时对象有什么问题。如果我不使用析构函数,那么一切都很好。 但是使用析构函数会产生问题。多项式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;
}
答案 0 :(得分:2)
您没有定义赋值运算符,因此当您执行p[2] = p[0] + p[1]
时,将使用默认赋值运算符,该运算符将p[2].coeff
指定为与coeff
的{{1}}相同的数组。由添加创建的临时对象。
因此,当临时对象被销毁时,它的析构函数会删除该数组,而p[2].coeff
现在是一个无效的指针。因此,访问它将导致未定义的行为。
复制构造函数也应该以{{1}}引用作为参数。
答案 1 :(得分:0)
如果在poly类中使用“ 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;
}