码迷,mamicode.com
首页 > 其他好文 > 详细

成员对象和封闭类

时间:2016-07-08 13:22:41      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

成员对象:类中的成员变量是另一个类的对象。包含成员对象的类叫做封闭类。

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

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

类名::构造函数(参数表):成员变量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;
}

 

 

 

成员对象和封闭类

标签:

原文地址:http://www.cnblogs.com/helloforworld/p/5652822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!