我想在C++中复制两个类似的结构。考虑以下三个结构。
struct Dest_Bio
{
int age;
char name;
};
struct Source_Bio
{
int age;
char name;
};
struct Details
{
int id;
Dest_Bio* st_bio; //Needs to be populated with values from Source_Bio
};
我尝试了以下方法。它可以正常编译,但会在运行时使程序崩溃。
Source_Bio st_ob;
st_ob.age = 5;
st_ob.name = 't';
Details st_a;
st_a.id = 1;
st_a.st_bio = (Dest_Bio*) malloc(sizeof(Dest_Bio));
memcpy((struct Dest_Bio*)&st_a.st_bio, (struct Source_Bio*)&st_ob,sizeof(Dest_Bio));
我该如何完成?提前致谢
最佳答案
简单的方法可能是这样的:
struct Dest_Bio {
int age;
char name; // should this really be a string instead of a single char?
Dest_Bio(Source_Bio const &s) : age(s.age), name(s.name) {}
};
Details st_a;
st_a.id = 1;
st_a.st_bio = new Dest_Bio(st_ob);
更好的是,您可能应该消除
Dest_Bio
和Source_Bio
,并仅将其替换为Bio
并用它完成。您几乎还肯定要用某种智能指针替换Dest_Bio *st_bio
-原始指针几乎在麻烦。或者,只需在Bio
对象内嵌入Details
对象(可能是首选)。关于c++ - 在C++中复制两个类似的结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19127546/