[英]How do I initialize a struct inside struct with members variables?
我定義了一個名為Object
的結構,在這個結構中還有 3 個結構。
collision_box
應該與position
和size
綁定在一起。 每當我更新 position 和尺寸時, collision_box
應該獲得相同的值。
在此之前,我只是將 position 和大小值復制到 Init 和 Update function 中的collision_box
。它工作正常,但我認為這也適用於指針,因此我不必每次都復制這些值。
// Object definition
typedef struct Object{
Vector2 position; // typedef struct float x,y
Vector2 size; // typedef struct float x,y
// When ever I update position and size the collision_box should get the same values
// without copying them in the Update function.
Rectangle collision_box = {position.x, position.y, size.x, size.y}; // typedef struct float x,y,width,height
}Object;
// Extension of Object
typedef struct Player{
Object* o;
}Player;
// Update Players position and size
void UpdatePlayer(Player* player)
{
player->o->position = (Vector2){100.0f, 100.0f};
player->o->size = (Vector2){20.0f, 20.0f};
}
// player.o->collision_box should always be tied to player.o->position and player.o->size
printf("%f/n", player.o->collision_box.x);
printf("%f/n", player.o->collision_box.y);
printf("%f/n", player.o->collision_box.width);
printf("%f/n", player.o->collision_box.height);
Output
100.0
100.0
20.0
20.0
您可以將Object
聲明為union
,而不是struct
,其中position
和size
成員本身包含在內部匿名結構中。
這樣,兩個Vector2
類型將占用與Rectangle
成員相同的 memory,並且對前者的任何更改也將對后者進行(反之亦然):
typedef union tagObject {
struct {
Vector2 position, size;
};
Rectangle collision_box;
}Object;
這使您能夠通過position
和size
成員,或通過collision_box
成員來引用數據。
測試代碼(將/n
更正為\n
並將一些局部變量添加到main
function 以便它工作):
int main()
{
Player player;
Object object;
player.o = &object;
UpdatePlayer(&player);
// player.o->collision_box should always be tied to player.o->position and player.o->size
printf("%f\n", player.o->collision_box.x);
printf("%f\n", player.o->collision_box.y);
printf("%f\n", player.o->collision_box.width);
printf("%f\n", player.o->collision_box.height);
}
Output:
100.000000
100.000000
20.000000
20.000000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.