共用方式為


Initializing Member Objects

Classes can contain member objects of class type, but to ensure that initialization requirements for the member objects are met, one of the following conditions must be met:

  • The contained object's class requires no constructor.

  • The contained object's class has an accessible default constructor.

  • The containing class's constructors all explicitly initialize the contained object.

The following example shows how to perform such an initialization:

// spec1_initializing_member_objects.cpp
// Declare a class Point.
class Point
{
public:
    Point( int x, int y ) { _x = x; _y = y; }
private:
    int _x, _y;
};

// Declare a rectangle class that contains objects of type Point.
class Rect
{
public:
    Rect( int x1, int y1, int x2, int y2 );
private:
    Point _topleft, _bottomright;
};

//  Define the constructor for class Rect. This constructor
//   explicitly initializes the objects of type Point.
Rect::Rect( int x1, int y1, int x2, int y2 ) :
_topleft( x1, y1 ), _bottomright( x2, y2 )
{
}

int main()
{
}

The Rect class, shown in the preceding example, contains two member objects of class Point. Its constructor explicitly initializes the objects _topleft and _bottomright. Note that a colon follows the closing parenthesis of the constructor (in the definition). The colon is followed by the member names and arguments with which to initialize the objects of type Point.

Note

The order in which the member initializers are specified in the constructor does not affect the order in which the members are constructed; the members are constructed in the order in which they are declared in the class.

Reference and const member objects must be initialized using the member initialization syntax shown in the Grammar section in Initializing Bases and Members. There is no other way to initialize these objects.

See Also

Reference

Initializing Bases and Members