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

更新日期:2019-07-30

386 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告