2013-04-12 70 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