提问者:小点点

C++编译时对结构中字段的引用


嗨,我有这样一个结构:

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

我试过两种方法,但其中一种要花内存,另一种要花性价比(我不确定):

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

有什么编译时间的方法吗?

谢了。


共2个答案

匿名用户

我建议你这样使用。

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

匿名用户

如果要通过其他别名访问,可以使用typedef

在之前声明

typedef a x;
typedef b y;

我建议使用唯一的,不会冲突的名称,而不是a,b或x,y,而且你也可以签出#define,这是一个预处理器指令,它做同样的事情

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|编译|结构|中|字段|引用)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?