当前位置: 代码迷 >> 综合 >> C++学习——静态对象的初始化问题
  详细解决方案

C++学习——静态对象的初始化问题

热度:34   发布时间:2024-01-15 14:26:03.0

我们设工程中有一个头文件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();

 

}





  相关解决方案