Computer >> Máy Tính >  >> Lập trình >> C ++

Toán tử độ phân giải phạm vi so với con trỏ này trong C ++

Toán tử phân giải phạm vi được sử dụng để truy cập các thành viên tĩnh hoặc lớp trong khi con trỏ này được sử dụng để truy cập các thành viên đối tượng khi có một biến cục bộ có cùng tên.

Toán tử phân giải phạm vi

Ví dụ

#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;
}

Đầu ra

the number is:7

con trỏ này

Ví dụ

#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;
}

Đầu ra

the number is: 6