您的位置:首页 > 编程语言 > C语言/C++

C++的构造与析构函数

2016-01-24 15:34 381 查看

Code

/*************************************************************************
> File Name: test.cpp
> Author: Fan Deliang
> Mail: fan0816fan@163.com
> Created Time: 2016年01月24日 星期日 15时15分35秒
************************************************************************/

#include<iostream>
using namespace std;
class a{
public:
a(){cout<<"a has constructed!"<<endl;}
~a(){cout<<"a is leaving !"<<endl;}
};
class b{
public:
b(){cout<<"b has constructed!"<<endl;}
~b(){cout<<"b is leaving !"<<endl;}
};
int main()
{
a A;
b B;
return 0;
}


Result

a has constructed!
b has constructed!
b is leaving !
a is leaving !






conclusion

普通的有关联的构造函数,比如:

class a{};

class b{};

class c:public b,public a{};

执行构造函数时:肯定是先构造b,再构造a,最后构造c;

执行虚构函数时:肯定是先析构c,然后是a,最后析构b;

符合先构造的后析构,后构造的先析构的原则;

但是对于我们上面那个例子,两者(a,b)貌似没有什么联系。经过实践检验,同样也符合,上述原则。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: