首页 > 其他 > 详细

~~~~~~~~~~~析构函数~~~~~~~~

时间:2016-02-29 21:35:30      阅读:281      评论:0      收藏:0      [点我收藏+]
 1 // 当 对象的 生命期 结束的时候 , 会自动执行析构函数 .  
 2 //  下面的程序 就是一个例子 
 3 //析构函数 (destructor) "~" ;  "~"为取反运算符  所以可以看出  析构函数是和 构造函数作用相反的的 函数 
 4 #include<iostream>
 5 #include<string>
 6 using namespace std;
 7 class student          //  声明一个 student 类
 8 {
 9 public:
10     student(int n,string nam,char s)  //构造一个  有参函数
11     {
12         num=n;
13         name=nam;
14         sex=s;
15         cout<<"Constructor called ."<<endl; //  输出 有关信息
16     }
17     ~student()              //定义  析构函数
18     {
19         cout<<" 程序 结束  调用 析构函数  "<<num<<endl;
20     }
21     void display()          //定义 成员函数
22     {
23         cout<<"num: "<<num<<endl;
24         cout<<"name: "<<name<<endl;
25         cout<<"sex: "<<sex<<endl;
26     }
27 private:       //   你懂得
28     int num;
29     string name;
30     char sex;
31 };
32 int main()
33 {
34     student stud1(10010,"wang_li",f);
35     stud1.display();
36     student stud2(10011,"zhang_feng",m);
37     stud2.display();
38     return 0;
39 }
40 //    这时候 运行一下程序会发现一个问题  为什么 是先运行 stud2 的析构函数 ?
41 /*      先构造的 后析构        相当于  一个先进 后出 的 栈  */  

 

~~~~~~~~~~~析构函数~~~~~~~~

原文:http://www.cnblogs.com/A-FM/p/5228844.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!