组合(composition)
组合就是一个类的对象作为另一个类的成员对象
比如
//class X;
class Y
{
private:
X x;
}
注意:
由于类Y中有类X的对象x,为了保证在初始化Y的对象之前正确初始化X中的x,C++中提供了初始化列表的方法可以显式的调用x的构造函数。
//x.h
class X
{
private:
int i;
public:
X(int val) { i = val; }
};
//end file
//y.h
#include"x.h"
class Y
{
private:
X x;
public:
Y(int val): x(val) {} //初始化列表
};
//end file
比如
//class X;
class Y
{
private:
X x;
}
注意:
由于类Y中有类X的对象x,为了保证在初始化Y的对象之前正确初始化X中的x,C++中提供了初始化列表的方法可以显式的调用x的构造函数。
//x.h
class X
{
private:
int i;
public:
X(int val) { i = val; }
};
//end file
//y.h
#include"x.h"
class Y
{
private:
X x;
public:
Y(int val): x(val) {} //初始化列表
};
//end file

浙公网安备 33010602011771号