沒有連結的名稱
有沒有連結的唯一名稱為:
函式的參數。
區塊範圍名稱並未宣告成extern或靜態。
列舉值。
在宣告名稱typedef陳述式。 例外狀況就是typedef陳述式用來提供未命名的類別類型的名稱。 名稱可能會再有外部連結,如果類別具有外部連結。 下列範例會示範一種情況的typedef名稱具有外部連結:
// names_with_no_linkage.cpp typedef struct { short x; short y; } POINT; extern int MoveTo( POINT pt ); int main() { }
typedef名稱, POINT,就會變成未命名的結構的類別名稱。 接著會使用它來宣告具有外部連結的函式。
因為typedef名稱沒有連結,其定義可以各不相同的轉譯單元。 編譯都會分開進行,因為沒有任何方法,編譯器才能偵測這些差異。 如此一來,這種類型的錯誤目前無法偵測到連結階段。 請考慮下列案例:
// Translation unit 1
typedef int INT
INT myInt;
...
// Translation unit 2
typedef short INT
extern INT myInt;
...
上述程式碼在連結階段產生 「 無法解析的外部 」 錯誤。
範例
C + + 函式可以定義只能在檔案或類別範圍中。 下列範例將示範如何定義函式,並顯示錯誤的函式定義:
// function_definitions.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
void ShowChar( char ch ); // Declare function ShowChar.
void ShowChar( char ch ) // Define function ShowChar.
{ // Function has file scope.
cout << ch;
}
struct Char // Define class Char.
{
char Show(); // Declare Show function.
char Get(); // Declare Get function.
char ch;
};
char Char::Show() // Define Show function
{ // with class scope.
cout << ch;
return ch;
}
void GoodFuncDef( char ch ) // Define GoodFuncDef
{ // with file scope.
int BadFuncDef( int i ) // C2601, Erroneous attempt to
{ // nest functions.
return i * 7;
}
for( int i = 0; i < BadFuncDef( 2 ); ++i )
cout << ch;
cout << "\n";
}