如何在 C++ 中宣告變數?


在 C++ 中,宣告和定義通常容易混淆。宣告是指(在 C 中)在程式中告知編譯器任何變數、使用者定義型別或函式的型別、大小和(在函式宣告中)其引數的型別和大小。宣告時不會為任何變數在記憶體中保留空間。

另一方面,定義是指除宣告執行的所有操作外,還另外在記憶體中保留空間。你可以說“定義 = 宣告 + 保留空間”。

以下是宣告示例 −

extern int a;                          // Declaring a variable a without defining it
struct _tagExample { int a; int b; };  // Declaring a struct
int myFunc (int a, int b);             // Declaring a function

以下是定義示例 −

int a;
int b = 0;
int myFunc (int a, int b) { return a + b; }
struct _tagExample example;

更新時間: 11-Feb-2020

494 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告