[英]copying constructor and operator= (multiple arrays…)
我必須為Reg類創建一個復制構造函數和賦值運算符=。 但我有復雜的結構,不知道如何正確復制它。 所以,問題是,如何為類Reg創建復制構造函數 - 淺拷貝? 另一個問題是,operator =應該如何 - 它應該是Reg的深層副本
struct TMoves
{
const char* ddate;
const char* sstreet;
const char* ccity;
public:
~TMoves()
{
delete [] ccity;
delete [] ddate;
delete [] sstreet;
}
};
struct TData
{
int stackmult;
const char* iid;
const char* nname;
const char* ssurname;
int pocet;
TMoves** moves;
public:
TData()
{
stackmult=1;
}
~TData()
{
delete [] iid;
delete [] nname;
delete [] ssurname;
for(int i=0;i<pocet;i++)
{
delete moves[i];
}
delete [] moves;
}
};
class Reg
{
public:
Reg ();
Reg (const Regr&);
~Reg();
Reg& operator= (const Reg &);
bool Add (const char* id, const char* name, const char* surname, const char* date, const char* street, const char* city );
bool Resettle ( const char* id, const char* date, const char* street, const char* city );
private:
static const int MAX=1000; //default lenght of pole
TData **pole;
int counter; // pole lenght counter - not important now
int multiplier; // used for realocating pole
};
Reg::Reg()
{
counter=0;
multiplier=1;
pole=new TData*[multiplier*MAX];
}
Reg::Reg(const Reg& out)
{
//... how?
}
Reg::Reg &operator= (const Reg& copy)
{
//... how?
}
在方法添加 - 在這里我找到正確的位置(misto)我應該在哪里放置id - 使用二進制搜索
int misto=counter;
pole[misto]=new TData;
char *temp = new char[12];
strcpy(temp, id);
pole[misto]->iid = temp;
temp = new char[strlen(name)+1];
strcpy(temp, name);
pole[misto]->nname = temp;
temp = new char[strlen(surname)+1];
strcpy(temp, surname);
pole[misto]->ssurname = temp;
pole[misto]->moves=new TMoves*[STAT];
pole[misto]->moves[0]=new TMoves;
temp = new char[strlen(city)+1];
strcpy(temp,city);
pole[misto]->moves[0]->ccity= temp;
temp = new char[strlen(date)+1];
strcpy(temp,date);
pole[misto]->moves[0]->ddate= temp;
temp = new char[strlen(street)+1];
strcpy(temp,street);
pole[misto]->moves[0]->sstreet= temp;
在方法Ressetle - 我找到id - 我必須找到的地方,我將添加另一個信息(城市,街道,日期),我創建新的TMoves:
pole[misto]->moves[misto2]=new TMoves;
char *temp = new char[strlen(city)+1];
strcpy(temp,city);
pole[misto]->moves[misto2]->ccity= temp;
temp = new char[strlen(date)+1];
strcpy(temp,date);
pole[misto]->moves[misto2]->ddate= temp;
temp = new char[strlen(street)+1];
strcpy(temp,street);
pole[misto]->moves[misto2]->sstreet= temp;
這個話題可能令人困惑,但我的代碼太長了,而且我只面臨着兩個復制問題。 感謝您的時間和回復。
不要給復制構造函數和復制賦值運算符賦予不同類型的語義。
默認情況下,兩者都應該提供一個獨立的副本。
復制構造函數的最佳實現是依賴成員的復制構造,只使用編譯器生成的構造。 為此,請使用std::string
而不是char*
,並將std::vector
用於其他數組。 就這么簡單。
對於已明確指示不使用string
和vector
的作業情況,請定義自己的類。
保持每個類最多管理一個資源的格言,例如動態分配的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.