`

《C++学习笔记》不同数据类型对象的构造函数和析构函数的调用顺序

    博客分类:
  • C++
阅读更多
===============================================
未完待续,转载时请表明出处:http://www.cofftech.com/thread-1400-1-1.html
欢迎大家跟帖讨论哈~~~~~
===============================================

现在看一下不同数据类型对象的构造函数和析构函数的调用顺序,从而看出它们的生命周期和作用域。
[例1]建立不同数据类型的对象时,构造函数和析构函数的调用顺序。
此程序按照数据隐藏类型处理,共有三个文件:cons_des.h,cons_des.cpp,cons_des_hide.cpp。其中不向用户提供cons_des_hide.cpp源文件而只提供cons_des_hide.obj目标文件
头文件:
// cons_des.h
#ifndef CONS_DES_H
#define CONS_DES_H
#include <iostream.h>
class base {
    int data;
public:
    base( int );  // constructor declaration
    ~base();      // destructor declaration
};
#endif
这是类的接口。
隐藏源文件:
// cons_des_hide.cpp
#include "cons_des.h"
base::base( int value ) : data(value)
{
    cout << "Object " << data << "   constructor";
}
base::~base()
{ cout << "Object " << data << "   destructor " << endl; }
主文件:
// cons_des.cpp
#include "cons_des.h"
void create( void );   // prototype
base first( 1 );  // global object
void main()
{
   cout << "   (globally created before main)" << endl;
   base second( 2 );        // local object
   cout << "   (local automatic in main)" << endl;
   static base third( 3 );  // local static object
    cout << "   (local static in main)" << endl;
   create( );  // call function to create objects
   base sixth( 6 );        // local object
   cout << "   (local automatic in main)" << endl;
}

// ordinary function for creating objects
void create( void )
{
   base fourth( 4 );
    cout << "   (local automatic in create)" << endl;
   static base fifth( 5 );
   cout << "   (local static in create)" << endl;
}

/* Results:
   Object 1        constructor   (globally created before main)
   Object 2        constructor   (local automatic in main)
   Object 3        constructor   (local static in main)
   Object 4        constructor   (local automatic in create)
   Object 5        constructor   (local static in create)
   Object 4        destructor
   Object 6        constructor   (local automatic in main)
   Object 6        destructor
   Object 2        destructor
   Object 5        destructor
   Object 3        destructor
   Object 1        destructor              */

以上程序中,当局部对象离开其作用域时,即离开其函数时,就被删除,从而调动其析构函数。
在主程序运行之前,已经建立第一个对象(即全局对象first),主程序运行之后,顺序地建立自动对象second和静态对象third。
接着调用函数create( ),在create( )中建立自动对象fourth和内部静态对象fifth,退出create( )时除静态对象fifth外,删除其它对象并调用它的析构函数,即fourth。
回至主程序后,建立自动对象sixth。
退出主程序时,先删除主程序内的自动对象并调用它们的析构函数,即fourth和second。然后删除内部静态对象并调用它们的析构函数,即second和fifth。最后删除主程序外的全局对象并调用它的析构函数,即first。
此外,当局部对象离开其作用域后,就无法再被访问。例如在主函数main( )中无法访问fourth对象,而在子函数create( )中则无法访问third对象。
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics