前置的双冒号也称为范围解析运算符。该运算符的一些用法如下。
范围解析运算符可用于在类外部定义函数。演示该程序的程序如下。
#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