2013-05-19 50 views
1

在我的代码中有operator +重载。在此范围内,我定义了要构建和返回的对象ans,但似乎析构函数在返回它之前会先破坏ans,所以此方法返回一些未定义的值。在我完成使用这个对象之前调用destructor来销毁对象

我不明白我错在哪里?它是析构函数,构建器,还是我的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; 
} 

感谢您的时间和帮助。

+0

你违反了[三规则(http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming))有蛋糕。 –

回答

4

您的运营商+返回一个新的vector1类的副本。
但是原始的(在函数的开头声明的)在块的末尾被破坏(在右括号}之前)。

然后析构函数删除内部数组arr
因此,复制的vector1对象指向已删除的数组。

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

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

当您从operator+返回ans浅拷贝是由留下vector1指向的两个实例相同的数据。当第一个实例超出范围时,它将删除两者都指向的数据。要纠正这一点,你需要一个拷贝构造函数,使深层副本添加到vector1

vector1(const vector1& other) 
{ 
    // make a deep copy from "other. 
} 
0

你没有定义这样一个默认的一个是由编译器生成的拷贝构造函数。

你的operator+返回一个shallow copy你的载体。 当ans在操作员结束时超出范围时,它会将数据带给他。

请阅读更多关于What is The Rule of Three?