您的位置:首页 > 其它

成员对象和封闭类

2016-07-08 11:31 281 查看
成员对象:类中的成员变量是另一个类的对象。包含成员对象的类叫做封闭类。

封闭类构造函数的初始化列表

定义封闭类的构造函数时,添加初始化列表:

类名::构造函数(参数表):成员变量1(参数表),成员变量2(参数表),….

{

. . .

}

成员对象初始化列表中的参数

任意复杂的表达式

函数/变量/表达式中的函数,变量有定义

调用顺序:

当封闭类对象生成时

Step1执行所有成员对象的构造函数

Step2执行封闭类的构造函数

成员对象的构造函数调用顺序和成员对象在类中的声明顺序一致与在初始化列表中出现的顺序无关。

当封闭类的对象消亡时:

Step1执行封闭类的析构函数

Step2执行成员对象的析构函数

析构函数调用顺序和构造函数调用顺序相反。

代码如下:

#include <iostream>

using namespace std;

class Engine
{
private:
int price;
public:
Engine(int p)
{
price = p;
cout << "Engine constructor is called" << endl;
}
~Engine()
{
cout << "Engine deconstructor is called" << endl;
}
};

class tyer
{
private :
int width, length;
public:
tyer(int w, int l) :width(w), length(l)
{
cout << "tyer constructor is called" << endl;
};
~tyer()
{
cout << "tyer destructor is called" << endl;
}
};

class car
{
private :
tyer ty;
Engine en;
int color;
public:
car(int col, int p, int w, int l);
~car()
{
cout << "car deconstructor is called" << endl;
}
};
car::car(int col, int p, int w, int l) :color(col), en(p), ty(w, l)
{
cout << "car constructor is called" << endl;
}

int main()
{
car car1(2, 1, 4, 5);
return 0;
}


参考链接:
https://www.coursera.org/learn/cpp-chengxu-sheji
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: