2014-03-02 25 views
0

嗨我正在從一個項目中獲取文件中的信息,然後將其放入一個對象數組中,然後通過菜單中的選項操縱對象中的數據。我目前遇到的問題是菜單中的一個選項是向對象添加一個新元素。該項目狀態,我必須使用一個對象數組,所以我不能只使用一個矢量我將數組放入其中的類來調整它的大小,它使用臨時動態數組作爲對象,然後刪除原始數組。在C++中調整對象的動態數組

這裏的類是什麼樣

class Info 
{ 
private: 
    string name; 
    double money; 
public: 
    Info(){ 
    name=""; 
    money=0; 
    } 

    void Setname(string n){ 
    name=n; 
    } 
    void Setmoney(double m){ 
    money=m; 
    } 
    string GetName()const{ 
     return name; 
    } 
    double GetMoney()const{ 
     return money; 
    } 
}; 

現在只是一個實際的類與它的方程改變貨幣變量的類的樣品,不過對於這個問題的目的,這是所有的需要。現在,這裏是我有問題

void Addinfo(Info in [], int & size){ 
     string newname; 
     double newmoney; 
     cout<<"What name are you going to use?"<<endl; 
     cin>>newname; 
     cout<<"Now How much money do you have currently"<<endl; 
     cin>>newmoney; 
     Info *temp= new Info[size+1]; 
     for(int index=0; index<size;index++){ 
      temp[index].Setname(in[index].GetName()); 
      temp[index].Setmoney(in[index].GetMoney()); 
     } 
     delete []in; 
     temp[size].Setname(newname); 
     temp[size].Setmoney(newmoney); 
     in=temp; 
     size=size+1; 
} 

現在,當我運行程序一切都正常運行,直到我嘗試使用此功能在陣列中的數據得到腐敗的功能。我是否應該讓Info變量成爲一個新的動態數組,它可以容納所有信息,然後使用另一個for循環將變量放入新的動態數組中,或者我應該做其他事情。還記得我必須爲此使用數組。另外,當刪除一個動態數組我是否應該刪除後使前一個數組等於零或是其他的東西?

+0

如果你想將'in'設置爲temp數組,你應該將它作爲指針的引用傳入。你的'in = temp'賦值現在沒有任何有用的效果,因爲'in'是通過值傳入的 – happydave

回答

0

當你有一個type valueName[]數組參數的函數,那麼你只需將該數組參數的地址傳遞給函數。調用函數擁有該數組的所有權。除了函數簽名外,您還必須考慮調用者和被調用函數之間的契約,該契約定義了指針傳遞的數據的所有權。

函數AddInfo獲取一個由指針傳遞的數組,並且調用函數期望數據在函數調用後可用。因此,當您delete []in時,該功能違反了合同。

當您爲in=temp;分配新值時,您的函數使用參數in作爲(本地)變量。這是合法的。但是你不能指望改變的局部變量對調用者有任何影響。在當前的函數簽名,可以調用該函數以這種方式:

Info infos[5]; 
Addinfo(&info[3], 2); 

很顯然,這是沒有意義的修改&info[3]。當你的合同允許向數組添加一些數據時,你需要一個允許改變指針的簽名。一個例子是:

void Addinfo(Info*& in, int& size, string newname, double newmoney) 
{ 
    Info *temp= new Info[size+1]; 
    for(int index=0; index<size;index++){ 
     temp[index].Setname(in[index].GetName()); 
     temp[index].Setmoney(in[index].GetMoney()); 
    } 
    temp[size].Setname(newname); 
    temp[size].Setmoney(newmoney); 
    delete []in; 
    in = temp; 
    size=size+1; 
} 

void Addinfo(Info*& in, int& size) 
{ 
    string newname; 
    double newmoney; 
    // input data 
    cout<<"What name are you going to use?"<<endl; 
    cin>>newname; 
    cout<<"Now How much money do you have currently"<<endl; 
    cin>>newmoney; 
    // TODO: data validation. 
    // add data to array 
    Addinfo(in, size, newname, newmoney); 
} 

我已經分析了從輸入數組的變化。這允許對該功能進行更簡單的測試。