Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 變量的持續性、作用域與連結性全解析

翻過 C++ Primer 之後,作者把「變量的持續性、作用域與連結性」這段略顯枯燥卻至關重要的內容做了提煉整理。理解這三者,是寫出正確且可維護的 C++ 程式的基礎功。

自動變量與寄存器變量

最常見的是自動變量,修飾符為 auto(通常省略),在程式區塊建立時誕生、區塊結束即消失,存放於堆疊中,堆疊一結束變量自然隨之消失。若把 auto 換成 register,編譯器就會改用暫存器來存放,省去記憶體開銷;但要注意,暫存器沒有位址,因此不能對寄存器變量使用取位址運算子。

靜態存儲與三種連結性

靜態存儲持續性有三種連結性:外部連結性、內部連結性與無連結性。下表整理了五種儲存方式的差異:

5 種變量儲存方式
存儲描述持續性作用域連結性如何聲明
自動自動程式區塊無在程式區塊中(auto)
寄存器自動程式區塊無在程式區塊中,用 register
靜態,無連結性靜態程式區塊無在程式區塊中,用 static
靜態,外部連結性靜態檔案外部在函式外面
靜態,內部連結性靜態檔案內部在函式外面,使用 static

外部連結性實例

下面這段以 static 修飾、具外部連結性的例子,說明了全域變量的「定義」與「聲明」之別,以及區域變量如何遮蔽外部變量:

#include <iostream>
using namespace std;
//注意 warming 變量
double warming = 0.3;                //全域變量 稱為定義,給變量分配存儲空間

void update(double dt);
void local();

int main(){
    cout << "Global warming is " << warming << " degrees.\n";
    update(0.1);
    cout << "Global warming is " << warming << " degrees.\n";
    local();
    cout << "Global warming is " << warming << " degrees.\n";
    return 0;
}

void update(double dt)
{
    extern double warming;          //引用外部變量 稱為聲明,不給變量分配存儲空間
    warming += dt;
    cout << "UPdating gloabal warming to " << warming;
    cout << " degrees.\n";
}

void local()
{
    double warming = 0.8;          //隱藏了外部變量 為0.8
    cout << "Local warming = " << warming << " degrees.\n";
    cout << "the global waming is " << ::warming;
}

內部連結性實例

接著是 static 修飾、內部連結性的兩個檔案。file1.cpp 定義了外部變量 tom、dick 與內部連結性的 harry:

#include <iostream>

int tom = 3;
int dick = 30;
static int harry = 300;     //內部連結性,只在該檔案內部可用。

void remote_access();

int main()
{
    using namespace std;
    cout << "main()reports the following addresses: \n";
    cout << &tom << " = &tom, " << &dick << " = &dick,";
    cout << &harry << " = &harry\n";
    cout << tom << ' ' << dick << ' ' << harry << ' ' << endl;         // 3 30 300
    remote_access();
    return 0;
}

file2.cpp 則透過 extern 引用外部的 tom,同時定義了自己的內部連結性 dick 與外部 harry:

#include <iostream>

extern int tom;
static int dick = 10;          //內部連結性
int harry = 200;

void remote_access()
{
    using namespace std;
    cout << "remote_access() reports the following address: \n";
    cout << &tom << " = &tom, " << &dick << " = &dick,";
    cout << &harry << " = &harry\n";
    cout << tom << ' ' << dick << ' ' << harry << ' ' << endl;         // 3 10 200
}

把這些程式跑一遍、對照輸出,連結性與作用域的差異便一目了然。作者原本還想接著談命名空間——那其實也是一種作用域——留待後續補上。

Copyright © Linux教程網 All Rights Reserved