[英]Loading parts of a struct into a another struct
我想将只有3个值的结构加载到只有2个值的结构中。
typedef struct {
double x;
double y;
} twod;
typedef struct {
double x;
double y;
double z;
} threed;
第二个结构包含3d平面的坐标数组。 目标是仅将x
和y
坐标从第二个结构加载到第一个结构中。
考虑到它们是不同的typedef,这可能吗? 解决方案将如何实施?
不,当然不可能,因为它不合适,因此不可能直接进行。
但是,您当然可以手动复制字段:
twod atwod;
threed athreed;
athreed.x = 1.0;
athreed.y = 2.0;
athreed.z = 3.0;
atwod.x = athreed.x;
atwod.y = athreed.y;
您可以做出可怕的假设并使用memcpy()
但这样做不值得。
当然,您还可以将所有基于继承的结构和threed
的结构进行threed
:
typedef struct {
twod xy;
double z;
} threed;
然后,您可以执行以下操作:
atwod = athree3.xy;
但是获取threed
变得不清楚。
您只需使用=运算符即可:
threed a = {1.0, 2.0, 3.0};
twod b;
b.x = a.x;
b.y = a.y;
继续展开想法:
typedef struct {
double x;
double y;
} twod;
typedef struct {
union {
struct {
double x;
double y;
};
twod xy;
};
double z;
} threed;
示例程序:
int main() {
threed vec = {1, 2, 3};
vec.y = 5;
twod v2 = vec.xy;
printf("x:%g y:%g z:%g\n", v2.x, v2.y, vec.z);
}
我相信这应该有效...
threed from;
from.x = 10;
from.y = 20;
from.z = 30;
twod to;
memcpy(&to, &from, sizeof(double) * 2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.