我有两个具有一些共同元素的不同结构。
typedef struct X {
struct X *next
char X1[5];
}
typedef struct Y {
unsigned char Y1;
int Y2[5];
bool Y3;
}Y;
typedef struct Z {
unsigned char Z1;
int Z2;
X X1;
Y Y1;
struct Z *next;
}Z;
typedef struct A {
unsigned char A1;
char A2[20];
X X1;
Y Y1;
}
typedef struct B {
unsigned char B1;
char B2[20];
int B3;
Z Z1;
}
我想复制 A 和 B,但我不想使用 reinterpret_cast,因为它有风险并且代码会部署在多台机器上。请建议任何优雅的复制方法。
附言我不允许更改设计。 :(
最佳答案
我想最优雅的方法是为 A
和 B
定义 operator=
,如下所示:
A & operator=(const B & b) {
this->A1 = b.B1;
memcpy(this->A2, b.B2, 20);
// Handle X1, Y1, B3 and Z1 somehow - depending on your needs
}
然后你可以这样调用它:
A a;
B b;
a = b;
无论如何,您需要分别处理每个元素。编译器不可能猜测您想如何处理不同类型的数据属性。
您可以进一步自动化该过程,例如通过为 Z
创建一个构造函数,该构造函数将采用 X
和 Y
的实例。
此外,请记住,提供复制构造函数和赋值运算符是一种很好的做法。
关于c++ - 如何在 C++ 中优雅地复制两个不同的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28893552/