2013-04-12 72 views
1

我想通過複製構造函數創建我的類的實例的深層副本,但我無法弄清楚,如何編寫它..在這一刻,當我調用複製構造函數,程序不會崩潰,但是當我想要對實例進行任何操作時(例如,打印數組,向其中添加一些項目等),那麼程序崩潰...複製構造函數中的深拷貝的問題

有人請告訴我,如何正確寫入?它的駕駛我瘋狂又O_O

struct DbChange { 
    const char* date; 
    const char* street; 
    const char* city; 
}; 

class DbPerson { 
public: 
    DbPerson(void); 
    const char* id; 
    const char* name; 
    const char* surname; 
    DbChange * change; 
    int position; 
    int size; 
}; 

DbPerson::DbPerson() { 
    position = 0; 
    size = 1000; 
    change = new DbChange[1000]; 
} 

class Register { 
public: 
    // default constructor 
    Register(void); 

    int size; 
    int position; 
    DbPerson** db; 

    //copy constructor 
    Register(const Register& other) : db() {  
     db= new DbPerson*[1000];  
     std::copy(other.db, other.db + (1000), db);  
    } 
}; 


int main(int argc, char** argv) { 
    Register a; 
    /* 
    * put some items to a 
    */ 

    Register b (a); 

    a . Print(); // now crashes 
    b . Print(); // when previous line is commented, then it crashes on this line... 

    return 0; 
} 
+0

什麼是你的空格鍵/ Tab鍵的問題?另外'註冊(void);'應該是'Register();' –

+3

你可以說'std :: string'男孩和女孩嗎?我知道你可以! –

+0

您是否嘗試過'a.Print()'而不創建b的實例?也許問題在別的地方。 –

回答

4

由於絕不所示的代碼可以讓我們猜測打印呢,爲什麼chashes,我就告訴你我是怎麼會想到事情在C++(而不是C和Java之間的尷尬的混合):

http://liveworkspace.org/code/4ti5TS$0

#include <vector> 
#include <string> 

struct DbChange { 
    std::string date; 
    std::string street; 
    std::string city; 
}; 

class DbPerson { 
    public: 
     DbPerson(void); 

     std::string id, name, surname; 
     int position; 
     std::vector<DbChange> changes; 

     size_t size() const { return changes.size(); } 
}; 

DbPerson::DbPerson() : position(), changes() { } 

class Register { 
    public: 
     size_t size() const { return db.size(); } 
     int position; // unused? 
     std::vector<DbPerson> db; 

     Register() = default; 

     //copy constructor 
     Register(const Register& other) : db(other.db) 
     { 
      // did you forget to copy position? If so, this would have been the 
      // default generated copy constructor 
     } 

     void Print() const 
     { 
      // TODO 
     } 
}; 


int main() { 
    Register a; 
    /* 
    * put some items to a 
    */ 

    Register b(a); 

    a.Print(); // now crashes 
    b.Print(); // when previous line is commented, then it crashes on this line... 

    return 0; 
} 
+0

打印寫得不錯,所以應該沒有問題 - 在調用copyconstructor打印之前,打印效果很好......並且正如您在我的文章中所看到的評論,我對包含的內容非常有限,因此我使用這些奇怪的構造...... .ehm ...和是...我也是很久以前的java程序員:D – Dworza

+1

打印可能會對'DbPersion :: change'或'Register :: db'中的單位化指針做些事情。不管寫得多好,總會有不明確的行爲 – sehe

+0

哦TY!那個該死的位置! :D我一直在尋找這個bug數小時,沒有注意到,我沒有複製位置值,因此我試圖訪問其他函數中的NULL值,因此程序崩潰:))有時我們看不到事情真的很明顯......哈哈......我現在有點慚愧:D – Dworza