C++ 預置雙冒號“::”是什麼意思?


預置雙冒號也被稱為作用域解析運算子。此運算子的一些用途如下。

在類外部定義函式

可以使用作用域解析運算子在類外部定義函式。演示此內容的程式如下。

範例

 線上演示

#include<iostream>
using namespace std;
class Example {
   int num;
   public:
   Example() {
      num = 10;
   }
   void display();
};
void Example::display() {
   cout << "The value of num is: "<<num;;
}
int main() {
   Example obj;
   obj.display();
   return 0;
}

輸出

以上程式的輸出如下。

The value of num is: 10

當存在具有相同名稱的區域性變數時,訪問全域性變數

當存在具有相同名稱的區域性變數時,可以使用作用域解析運算子訪問全域性變數。演示此內容的程式如下。

範例

 線上演示

#include<iostream>
using namespace std;
int num = 7;
int main() {
   int num = 3;
   cout << "Value of local variable num is: " << num;
   cout << "\nValue of global variable num is: " << ::num;
   return 0;
}

輸出

以上程式的輸出如下。

Value of local variable num is: 3
Value of global variable num is: 7

更新日期: 2020 年 6 月 26 日

7K+ 瀏覽量

開啟您的事業

完成課程,認證上崗

開始
廣告
© . All rights reserved.