我正在尝试通过复制构造函数创建类实例的深层拷贝,但我不知道如何编写它。此时,当我调用复制构造函数时,程序不会崩溃,然而,当我想对实例做任何事情时(即打印数组、向其添加一些项目等),程序就会崩溃...
有人可以告诉我如何正确编写吗?这让我发疯了 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;
}
最佳答案
由于显示的代码无法让我们猜测 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;
}
关于c++ - 复制构造函数中的深层复制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15981763/