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;
}
4

1 回答 1

4

由于显示的代码无法让我们猜测 Print 做了什么,以及它为什么会出现问题,所以我将向您展示我对 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;
}
于 2013-04-12T22:34:05.377 回答