gpt4 book ai didi

c++ - 在我使用完这个对象之前调用析构函数来销毁对象

转载 作者:行者123 更新时间:2023-11-30 01:22:17 25 4
gpt4 key购买 nike

在我的代码中有 operator+ 重载。在此范围内,我定义了对象 ans,我想构建并返回它,但在我返回它之前,析构函数似乎破坏了 ans,因此此方法返回了一些未定义的值。

我不明白我哪里错了?是析构函数、构建器还是我重载的 operator+?

这是我的代码:

class vector1{
int * arr;
int size;
public:
//constructors
vector1(){}
vector1(int n){
size=n;
arr= new int[size];
}
//functions
int get_size(){return size;}

void init(){ //initialize all array cells to 0
for(int i=0;i<size;i++)
arr[i]=0;
}
int get_value_in_index(int index){
return arr[index];
}
void set_value_in_index(int i, int num){
arr[i]=num;
}
int & operator[](int i){
int default_val=0;
if (i<0 || i>size){
cout<<"index not valid"<<endl;
return default_val;
}
return arr[i];
}
vector1 operator+(vector1 & ob);

//destructor
~vector1(){
delete [] arr;
}
};

vector1 vector1:: operator+(vector1 & ob){
vector1 ans(size);
if (ob.get_size()!=size){ //if the arrays are not the same size return array of '0', this array size
cout<<"vectors not the same length. can't sum them"<<endl;
//test
//exit(1);
ans.init();
}
else{
for (int i=0;i<size;i++)
ans.set_value_in_index(i,arr[i]+ob.get_value_in_index(i));
}
return ans;
}

感谢您的宝贵时间和帮助。

最佳答案

您的 operator+ 返回一个新的 vector1 类的拷贝。
但是原始的(在函数开头声明的)在 block 的末尾(右括号 } 之前)被销毁。

然后析构函数删除内部数组arr
所以复制的vector1对象指向一个删除的数组。

您应该创建一个复制构造函数来复制内部数组。

vector1(const vector1& _other ){
//copy .arr from the other one to this one
}

关于c++ - 在我使用完这个对象之前调用析构函数来销毁对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16634827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com