范围解析运算符用于访问静态或类成员,而当存在具有相同名称的局部变量时,此指针用于访问对象成员。
#include<iostream>
using namespace std;
class AB {
static int x;
public:
//局部参数'x'隐藏类成员
//'x',但我们可以使用::进行访问。
void print(int x) {
cout<<"t他的号码是:" << AB::x;
}
};
//那样明确定义
int AB::x = 7;
int main() {
AB ob;
int m = 6 ;
ob.print(m);
return 0;
}输出结果
t他的号码是:7
#include<iostream>
using namespace std;
class AB {
int x;
public:
AB() {
x = 6;
}
//这里本地参数“ x”隐藏对象的成员
//'x',我们可以使用它来访问它。
void print(int x) {
cout<<"t他的号码是: " << this->x;
}
};
int main() {
AB ob;
int m = 7 ;
ob.print(m);
return 0;
}输出结果
t他的号码是: 6