作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的代码中有 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/
我们面临一个用例,我们需要在 S3 上存储用户的 secret 图像。现在 S3 可以通过 HTTP 访问,如果我们授予对对象的读取权限,它们将通过 Web 提供给全世界。我们需要将图像/文件仅限于该
我是一名优秀的程序员,十分优秀!