zoukankan      html  css  js  c++  java
  • C++学习——静态对象的初始化问题

    我们设工程中有一个头文件depend.h, 在该头文件中我们声明了一个类——initial, 同是定义了一个initial类的静态对象——static initial init。

    代码如下所示:

    //////////////////////////////////////////////////////////
    // 文件:depend.h
    //////////////////////////////////////////////////////////
    #ifndef DEPEND_H_
    #define DEPEND_H_

    #include <iostream>
    using namespace std;

    class initializer
    {
    public:
     initializer()
     {
      cout << "initializer: "<<endl; 
     }
     ~initializer()
     {
      cout << "~initializer:" << endl;
     }
    };

    static initializer init;

    #endif

    同时我们在三个.cpp文件中都包含了depend.h这个头文件。 这个时候编译器在编译这三个.cpp的文件的时候就会分别生成三个名称为init的静态对象,由于静态对象的作用域只局限在当前文件内,所以三个静态对象重名不会在程序连接时产生错误,因为他们对于当前文件外的代码是透明的。我们通过在三个.cpp文件中定义三个函数用于输出它的init对象的首地址来表示三个.cpp文件中的init对象不是同一个对象.

    代码如下:

    /////////////////////////////////////////////////////////////
    // 文件:depend.cpp
    /////////////////////////////////////////////////////////////
    #include "depend.h"
    void OutClassAddress()
    {
     cout << "The starting address of the static object allocate in file:depend.cpp" << endl;
     cout << & init << endl;
    }

    /////////////////////////////////////////////////////////////
    // 文件:depend1.cpp
    /////////////////////////////////////////////////////////////
    #include "depend.h"
    void OutClassAddress1()
    {
     cout << "The starting address of the static object allocate in file:depend1.cpp" << endl;
     cout << & init << endl;
    }

    /////////////////////////////////////////////////////////////
    // 文件:depend2.cpp
    /////////////////////////////////////////////////////////////
    #include "depend.h"
    void OutClassAddress2()
    {
     cout << "The starting address of the static object allocate in file:depend2.cpp" << endl;
     cout << & init << endl;
    }

    extern void OutClassAddress(); //声明这个函数在别的文件中已经定义过了,告诉编译器放行,连接器在连接的时候会自动到别的文件中找这个函数
    extern void OutClassAddress1();

    void mian()

    {

        OutClassAddress();
        OutClassAddress1();
        OutClassAddress2();

    }





  • 相关阅读:
    [NOIP2010]关押罪犯
    图的联通入门题
    【luogu4777】扩展中国剩余定理(EXCRT)[数论 扩展中国剩余定理]
    【luogu3868】【TJOI2009】猜数字[模板] [数论 中国剩余定理]
    【luogu1082】【noip2012】同余方程 [数论 扩展欧几里德]
    【luogu1962】斐波那契数列 [矩阵乘法]
    【uva1644】 素数间隔 Prime Gap [数学 质数筛]
    【uva307】小木棍 Sticks [dfs搜索]
    【luogu4011】孤岛营救问题(拯救大兵瑞恩) [最短路][分层思想]
    【noip2015】
  • 原文地址:https://www.cnblogs.com/liulaolaiu/p/11744599.html
Copyright © 2011-2022 走看看