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