我想在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”结构中填充了值
  • 我想将Source_Bio中的这些值复制到“Details”结构中的st_bio中。
  • 我不想为Dest_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_BioSource_Bio,并仅将其替换为Bio并用它完成。您几乎还肯定要用某种智能指针替换Dest_Bio *st_bio -原始指针几乎在麻烦。或者,只需在Bio对象内嵌入Details对象(可能是首选)。

    关于c++ - 在C++中复制两个类似的结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19127546/

    10-12 07:40
    查看更多