c++ - c ++编译时对struct中的字段的引用
问题描述
嗨,我有一个这样的结构:
struct float2 {
float a;
float b;
};
现在我可以访问这样的成员:
float2 f;
f.a = 1;
f.b = 2;
我也想用其他别名访问 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
必须参考同样的记忆a
并且y, h, height
必须参考b
我尝试了 2 种方法,但其中一种消耗内存,一种成本性能(我不确定):
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;
}
};
有没有编译时的方法?
谢谢。
解决方案
我建议你这样使用。
#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;
}
推荐阅读
- javascript - js中按钮的背景颜色没有改变
- .net - 简单的注入器和 Mapster 依赖注入设置
- swiftui - 如何制作一个接受任何对象的 swiftui viewmodifier?
- c# - 在 ASP.NET MVC 项目中使用来自其他项目的自定义 Redis 序列化程序
- jenkins - 停电后,Jenkins 不再管理连接到 SVN 存储库
- scala - 为具有构造函数的类型创建扩展方法,是否需要类型约束?
- javascript - TS 配置 JSX:ReactJSX 与 React
- constraint-programming - 检查 Docplex CP 解决方案中的可行性和未满足的约束
- aix - 即使已经安装了 bff,也要安装它
- reactjs - 如何处理错误 401(未经授权)React-Laravel