类可以包含类类型成员对象,但是,确保成员对象的初始化要求匹配,必须满足以下条件之一:
包含的对象类不需要构造函数。
包含的对象类有一个可访问的默认构造函数。
包含类的构造函数都显式初始化包含的对象。
下面的示例演示如何执行方式初始化:
// 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 必须初始化成员对象使用在 初始化的基础和成员的语法部分显示的成员初始化语法。没有其他方式初始化这些对象。
说明