鱼C论坛

 找回密码
 立即注册
查看: 3033|回复: 3

程序执行的顺序

[复制链接]
发表于 2012-2-13 15:21:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <iostream>
using namespace std;

class A
{
        public:
        A()
        {
                cout<<"构造"<<endl;
        }       
        ~A()
        {
                cout<<"析构"<<endl;
        }
};
void show()
{
        cout<<"内外函数"<<endl;
}
int main()
{
        A a;
        show();
        return 0;
}
请问为什么show()函数的执行不是在a构造和析构完成后?
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-2-14 14:19:42 | 显示全部楼层
这个你要去理解一下类构造函数与析构函数的用途了、、、析构函数是在本对象需要删掉的时候经行析构函数。。。上例中、a在程序结束时,才经行析构(也就是删除),在show函数后面。。。
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-2-14 15:34:40 | 显示全部楼层
:LLS 2位头像一样,我还以为在自问自答
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-2-14 19:53:27 | 显示全部楼层
因为你定义的是对象 和 main里面变量生命期一样的
return 0时按F11才析构的
如果你定义对象前后加{} 变成块作用域试试
给你贴个代码 这个昨天学得 蛮有用得 分析好了下面这段代码就懂了构造顺序 析构顺序
指向对象 一些问题
----------------------------------------------------------
  1. // 构造析构顺序.cpp : Defines the entry point for the console application.
  2. //

  3. #include "stdafx.h"
  4. #include <iostream.h>

  5. //先成员构造 ---> 自己构造  
  6. //自己析构   ---> 先成员析构
  7. class B
  8. {
  9. public:
  10.     B()
  11.     {
  12.         cout << "B(): " << hex << this << endl;
  13.     }
  14.     ~B()
  15.     {
  16.         cout << "~B(): " << hex << this << endl;
  17.     }
  18. };

  19. class C
  20. {
  21. public:
  22.     C()
  23.     {
  24.         cout << "C(): " << hex << this << endl;
  25.     }
  26.     ~C()
  27.     {
  28.         cout << "~C(): " << hex << this << endl;
  29.     }
  30. };

  31. class A
  32. {
  33. public:
  34.     A* theA;
  35.     B theB;
  36.     C theC;
  37.     A()
  38.     {
  39.         cout << "A(): " << hex << this << endl;
  40.     }
  41.     A( const A& obj ):theC(),theB()
  42.     {
  43.         cout << "A() const A& obj: " << hex << this << endl;
  44.     }
  45.     ~A()
  46.     {
  47.         cout << "~A(): " << hex << this << endl;
  48.     }
  49. };

  50. A Fun(A obj)
  51. {
  52.     return obj;
  53. }

  54. int main(int argc, char* argv[])
  55. {
  56.     A obj1;
  57.    
  58.     A* lpobj2 = &Fun(obj1);
  59.    
  60.     A& obj2   = Fun(obj1);
  61.    
  62.     return 0;
  63. }

复制代码
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-11 08:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表