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

 

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值