初始化成员对象

类可包含类类型的成员对象,但为了确保满足成员对象的初始化要求,必须满足下列条件之一:

  • 包含的对象的类不需要任何构造函数。

  • 包含的对象的类具有一个可访问的默认构造函数。

  • 包含类的构造函数全部显式初始化包含的对象。

以下示例演示如何执行此类初始化:

// 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()
{
}

前面的示例中显示的 Rect 类包含类 Point 的两个成员对象。 其构造函数显式初始化对象 _topleft 和 _bottomright。 请注意,冒号跟在构造函数(在定义中)的右括号之后。 冒号后跟用来初始化 Point 类型的对象的成员名称和参数。

备注

构造函数中指定成员初始值设定项的顺序不影响成员的构造顺序;将按在类中声明成员的顺序来构造成员。

引用和 const 成员对象必须使用初始化基类和成员的“语法”一节中所示的成员初始化语法进行初始化。 没有其他方法可用来初始化这些对象。

请参见

参考

初始化基类和成员