结构体和联合体各自的基本用法不赘述,仅说一下他们匿名时访问的情况。如果是token不同,可以直接跨层访问。例子
- #include <iostream>
-
using namespace std;
-
-
struct zoo_obj{
-
string name;
-
union {
-
unsigned int property;
-
struct{ //plant
-
unsigned int
-
hasLeaf:1,
-
hasFlower:1,
-
hasTrunk:1,
-
hasRattan:1;
-
};
-
struct { //animal
-
unsigned int
-
isBackbone:1,
-
isOvipara:1,
-
hasLags:1,
-
hasWing:1;
-
};
-
};
-
-
};
-
-
int main(void)
-
{
-
zoo_obj peony = {"peony",0};
-
zoo_obj dog = {name:"dog",0};
-
dog.hasLags = true;
-
/* zoo_obj dog = {name:"dog",property:0};
-
* sorry, unimplemented: non-trivial designated initializers
-
* not supported
-
*/
-
-
cout << peony.name << " hasLeaf " << peony.hasLeaf << endl;
-
cout << dog.name << " hasLags " << dog.hasLags << endl;
-
-
}
输出
- peony hasLeaf 0
-
dog hasLags 1
不支持像列子中name样的指定访问。如果指定了会报错
- sorry, unimplemented: non-trivial designated initializers not supported