在C++中复制两个类似的结构
Copy two similar structures in C++
我想在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中的值复制到"详细信息"结构中的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_Bio
并Source_Bio
并用Bio
替换两者并完成它。你也几乎肯定想用某种智能指针替换你的Dest_Bio *st_bio
——一个原始指针几乎是在自找麻烦。或者,只需在Details
对象中嵌入一个Bio
对象(可能是首选)。
由于您已经要求两种Bio
类型都与布局兼容,因此请创建一个通用类型Bio
。然后在 C++ 而不是 C 中执行复制:
st_a.st_bio = new Bio(st_ob);
如果它们确实需要是不同的类型,则可以通过构造函数或转换运算符使Source_Bio
可转换为Dest_Bio
。
这是假设您对第三个要求有真正的理由(它是指针而不是成员)。否则,使其成为成员,修复潜在的内存泄漏,并进一步简化代码:
st_a.st_bio = st_ob;
如果你真的想用C函数来混沦,那么你要复制到st_a.st_bio
,而不是&st_a.st_bio
(即覆盖对象,而不是指向它的指针)。只有当你讨厌任何将维护代码的人时,才这样做。
相关文章:
- 在两个结构之间共享数组
- C++ 如何从函数传递两个结构?
- 如何认为两个结构相等,而不管它们的第二个属性如何?
- 使用用户函数在 C++ 中交换两个结构
- 在CPP中互相访问的两个结构
- 如何实现 std::map::查找包含两个结构'Pos'结构的比较逻辑,每个结构包含 x 和 y 坐标
- 当我们在两个结构上使用它时,= 运算符会做什么
- 合并/连接两个结构
- C++(SDL2)中的碰撞函数.如何传递存储在不同向量中的两个结构
- 具有相同名称和不同模板参数的两个结构如何工作
- 复制两个结构指针时出现分段错误
- Xcode 不链接两个结构
- 在两个结构(函子)中理解typedef的作用域
- 如何在c++中比较两个结构字符串
- 设置两个结构体相等后,指针为NULL
- 如何声明具有other类型成员的两个结构体
- 如何在c++中连接两个结构体类型变量
- C++ stl 列出了两个结构交叉引用
- 有两个结构在C++中相互引用彼此的变量
- 为什么我的两个结构数组没有相互作用?