[英]c++ compile time reference to field in struct
Hi i have an struct like this:嗨,我有一个这样的结构:
struct float2 {
float a;
float b;
};
now i can access members like this:现在我可以访问这样的成员:
float2 f;
f.a = 1;
f.b = 2;
i want to access a and b with other alias as well:我也想用其他别名访问 a 和 b :
float2 f;
f.a = 1;
f.b = 2;
f.x = 3;
f.y = 4;
f.w = 5;
f.h = 6;
f.width = 7;
f.height = 8;
x, w, width
must refer too same memory of a
and y, h, height
must refer to b
x, w, width
必须参考a
和y, h, height
必须参考b
相同的memory
i tried 2 ways but one of them cost memory and one cost performance( i'm not sure ):我尝试了 2 种方法,但其中一种花费 memory 和一种性价比(我不确定):
struct float2
{
float a;
float b;
// plan a ->
float& x;
float& y;
float& w;
float& h;
float2(float _a, float _b) : a(_a), b(_b), x(a), y(b), w(a), h(b) {}
// plan b ->
float& width() {
return a;
}
float& height() {
return b;
}
};
is there any compile time way?有没有编译时的方法?
thanks.谢谢。
I suggest you that use like this way.我建议你这样使用。
#include <stdio.h>
struct float2 {
union {
float a;
float x;
float w;
float width;
};
union {
float b;
float y;
float h;
float height;
};
};
int main()
{
float2 var1;
var1.x = 10.0;
var1.a = 12.0;
var1.w = 14.0;
var1.y = 0.0;
var1.h = 4.0;
var1.height = 6.0;
printf("a = %f x = %f w = %f width = %f\n", var1.a, var1.x, var1.w, var1.width);
// OUTPUT: a = 14.000000 x = 14.000000 w = 14.000000 width = 14.000000
printf("b = %f y = %f h = %f height = %f\n", var1.b, var1.y, var1.h, var1.height);
// OUTPUT: b = 6.000000 y = 6.000000 h = 6.000000 height = 6.000000
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.