C++ 中的作用域解析运算符与 this 指针
作用域解析运算符用于访问静态成员或类成员,而 this 指针用于访问对象成员(如果存在同名局部变量)。
作用域解析运算符
示例
#include<iostream>
using namespace std;
class AB {
static int x;
public:
// Local parameter 'x' hides class member
// 'x', but we can access it using ::.
void print(int x) {
cout<<"the number is:" << AB::x;
}
};
// static members must be explicitly defined like below in c ++
int AB::x = 7;
int main() {
AB ob;
int m = 6 ;
ob.print(m);
return 0;
}输出
the number is:7
this 指针
示例
#include<iostream>
using namespace std;
class AB {
int x;
public:
AB() {
x = 6;
}
// here Local parameter 'x' hides object's member
// 'x', we can access it using this.
void print(int x) {
cout<<"the number is: " << this->x;
}
};
int main() {
AB ob;
int m = 7 ;
ob.print(m);
return 0;
}输出
the number is: 6
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP