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();

    }





  • 相关阅读:
    策略模式c++【转】
    [转]C++设计模式:Builder模式
    c/c++ 笔试面试题
    堆排序
    冒泡,快速,和堆排序
    C++继承
    【转】林建:计算机专业学习浅谈
    (centos)linux下访问双系统windows7文件系统
    sprintf() in c
    System call in linux by C
  • 原文地址:https://www.cnblogs.com/liulaolaiu/p/11744599.html
Copyright © 2011-2022 走看看