構造体を用いることで、任意の型の要素をまとめられます。
struct MyStruct {
char a;
int* b;
};
C++の構造体とクラスの違いは、メンバが既定でpublicであることだけです。
[template-spec] struct [ms-decl-spec] [tag [: base-list ]]
{
member-list
} [declarators];
struct (C++ ) | MSDN
占有するビット数を指定してフィールドを定義します。このとき名前のないフィールドも認められ、それはレイアウトの調整に役立ちます。フィールドは整数か列挙型でなければならず、フィールドのアドレスは取得できません。
struct MyStruct {
bool a : 1;
bool b : 1;
bool : 1; // 名前なし
int c : 8;
};
配列と同様の方法で初期化できます。
struct MyStruct
{
int num;
char* p;
char a[2];
};
MyStruct s1 = { 5, "abc", {10,20} };
// s1.num ... 5
// s1.p ... "abc"
// s1.a[0] ... 10
// s1.a[1] ... 20
値を指定しないと、ゼロ初期化されます。
MyStruct s2 = {};
// s2.num ... 0
// s2.p ... NULL
// s2.a[0] ... 0
// s2.a[1] ... 0
MyStruct s3{}; // s2と同じ
初期化子を指定しないと、Visual C++では0xc (0b1100) で埋められます。
MyStruct s4; // s4.num ... 0xcccccccc (-858993460) // s4.p ... 0xcccccccc // s4.a[0] ... 0xcc (-52) 'フ' // s4.a[1] ... 0xcc (-52) 'フ'
または、かっこ内の式でも可能です。
MyStruct myStruct(1, "A", {1,2});
Cとの互換性から、structキーワードを付けても定義できます。
struct MyStruct myStruct;
これは同一スコープに同名の非構造体が宣言されている場合、それと区別するために必要です。
struct MyStruct {};
void MyStruct();
しかし、そもそもそのような曖昧な名前が付けられているのが問題で、通常はstructキーワードは不要です。
識別子を付けずに構造体を宣言できます。
struct
{
int a;
} myStruct;
void main()
{
myStruct.a = 10;
}
匿名構造体 - 匿名クラス型 | MSDN
この匿名構造体は、次のように構造体をネストするときに便利です。
struct MyStruct2
{
struct
{
int a;
} myStruct1;
int b;
} myStruct2;
void main()
{
myStruct2.myStruct1.a = 10;
myStruct2.b = 10;
}