1. 程式人生 > >C++學習——靜態物件的初始化問題

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

}