2013-05-19 49 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?