首页 > 解决方案 > 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;
    }
};

有没有编译时的方法?

谢谢。

标签: c++classstructreference

解决方案


我建议你这样使用。

#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;
}

推荐阅读