Loading... ## 匿名Union/Struct 最近看代码,看到了一个`union`/`struct`的特性,之前一致没察觉到。写上来记录一下 ```cpp #include <iostream> struct Point { union { float data[3]; struct { float x; float y; float z; }; }; }; int main(int argc, char** argv) { Point p; p.data[0] = 1; p.data[1] = 2; p.data[2] = 3; std::cout << p.x << std::endl; std::cout << p.y << std::endl; std::cout << p.z << std::endl; return 0; } ``` 程序返回内容如下 ``` 1 2 3 ``` 我们可以发现`Point`这个类中可以直接访问`x` `y` `z`和`data`。这里实际上利用了匿名`union`/`struct`的注入特性。 ## 匿名union/struct的注入特性 1. 如果在代码中使用匿名的`union`和`struct`,`union`和`struct`内部的变量会注入到`union`和`struct`的作用域中 ## Ref 1. https://en.cppreference.com/w/cpp/language/union 2. https://en.cppreference.com/w/c/language/struct Last modification:June 11, 2021 © Allow specification reprint Like If you think my article is useful to you, please feel free to appreciate