クラス型を使用して、そのクラス型のインスタンスつまりオブジェクト
を作成することができます。
例えば、クラス名の X、Y、および Z を指定 して、それぞれクラス、構造体、および共用体を宣言することができます。
class X { // members of class X }; struct Y { // members of struct Y }; union Z { // members of union Z };
これで、各クラス型のオブジェクトを宣言することができます。 クラス、構造体、および共用体は、すべて C++ クラスの型であることを忘れないでください。
int main() { X xobj; // declare a class object of class type X Y yobj; // declare a struct object of class type Y Z zobj; // declare a union object of class type Z }
C++ では、C とは異なり、クラスの名前が隠れていない限り、クラス・オブジェクトの宣言の前に、 キーワード union、struct、および class を入れる必要はありません。 次に例を示します。
struct Y { /* ... */ }; class X { /* ... */ }; int main () { int X; // hides the class name X Y yobj; // valid X xobj; // error, class name X is hidden class X xobj; // valid }
1 つの宣言で複数のクラス・オブジェクトを宣言すると、宣言子は個々に宣言されたように 扱われます。例えば、以下のように、クラス S の 2 つのオブジェクトを単一の宣言で 宣言する場合、
class S { /* ... */ }; int main() { S S,T; // declare two objects of class type S }
この宣言は、以下と同等です。
class S { /* ... */ }; int main() { S S; class S T; // keyword class is required // since variable S hides class type S }
しかし、以下と同等ではありません。
class S { /* ... */ }; int main() { S S; S T; // error, S class type is hidden }
また、クラスへの参照、クラスへのポインター、およびクラスの配列を宣言す ることもできます。次に例を示します。
class X { /* ... */ }; struct Y { /* ... */ }; union Z { /* ... */ }; int main() { X xobj; X &xref = xobj; // reference to class object of type X Y *yptr; // pointer to struct object of type Y Z zarray[10]; // array of 10 union objects of type Z }
コピー制限のないクラス型のオブジェクトは、関数への引き数として、代入または 引き渡しを行うことができ、また関数により戻すことができます。
関連参照