C 全域性變數類

2021-10-06 09:46:40 字數 1020 閱讀 3625

以一種更安全,更健壯的方式來表示全域性變數的方法,是將其封裝成全域性變數類,主要涉及以下的知識點:

示例:全域性變數的一般寫法

string program_name;

string version_stamp;

int version_number;

int tests_run;

int tests_passed;

改寫成全域性變數類進行管理:

public:

// 只能通過function member介面呼叫,將資料隱藏

static int test_passed()

static int tests_run()

static int version_number()

static string version_stamp()

static string programe_name()

static int test_passed()

// 提供可修改的function member

static void tests_run(int nval)

static void version_number(int vnal)

static void version_stamp(const string& nstamp)

static void programe_name(const string& npn)

private:

// 希望每個全域性變數都僅有乙個,所以定義為static member

static string _program_name;

static string _version_stamp;

static int _version_number;

static int _tests_run;

static int _tests_passed;

};// 定義示例,注意這裡只能定義全域性變數,如果放在main函式裡面就不能訪問!

int main()

c 全域性變數 靜態全域性變數

全域性變數是靜態儲存方式,靜態全域性變數也是靜態儲存方式,這兩者在儲存方式上並無不同。區別 雖在於非靜態全域性變數的作用域是整個源程式,當乙個源程式由多個原始檔組成時,靜態全域性變數在各個原始檔中都是有效的。靜態區域性變數則限制了其作用域,只在定義該變數的原始檔內有效,在同一源程式的其它原始檔中不能...

C 全域性變數

c 工程有以下幾個檔案 標頭檔案 a.h,b.h 相應的cpp檔案 a.cpp 包含a.h b.cpp 包含b.h 以及其他一些相關的.h,cpp檔案。a中有類a,b中有類b。現在需要在b.cpp中使用a.cpp 類a中的乙個變數,且希望其是隨著a.cpp 類a的呼叫更新的值。可按如下操作 在a.h...

c全域性變數

c語言中全域性變數可以重複定義 include int g val int g val 1 int main void 執行結果 1 include int g val 2 int g val int main void 執行結果 2 include int g val 2 int g val 1 ...