1. 程式人生 > >在c++標頭檔案中使用static修飾的全域性變數

在c++標頭檔案中使用static修飾的全域性變數

使用static修飾在標頭檔案中修飾的變數,此時不會產生衝突(用static修飾的全域性變數的作用域為定義的原始檔),在多個原始檔中引用該標頭檔案,等於是在每個原始檔中都定義了該變數一次,而且此變數僅在本原始檔中有效,這樣的使用方式不是本身想要的全域性變數,也浪費了記憶體空間,不推薦使用
eg:

test.h:
#ifndef TEST_H
#define TEST_H

#include <iostream>

using namespace std;

static int gi;

void print_test();
#endif

test.cpp:
#include "test.h"
void print_test() { gi++; cout <<&gi<<":"<< gi<< endl; } main.cpp: #include "test.h" #include <iostream> using namespace std; int main() { print_test(); cout <<&gi <<":"<<gi << endl; return 0; } 執行結果:

這裡寫圖片描述