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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP