
- C++ 基礎
- C++ 首頁
- C++ 概述
- C++ 環境搭建
- C++ 基本語法
- C++ 註釋
- C++ Hello World
- C++ 省略名稱空間
- C++ 常量/字面量
- C++ 關鍵字
- C++ 識別符號
- C++ 資料型別
- C++ 數值資料型別
- C++ 字元資料型別
- C++ 布林資料型別
- C++ 變數型別
- C++ 變數作用域
- C++ 多個變數
- C++ 基本輸入/輸出
- C++ 修飾符型別
- C++ 儲存類
- C++ 運算子
- C++ 數字
- C++ 列舉
- C++ 引用
- C++ 日期和時間
- C++ 控制語句
- C++ 決策
- C++ if 語句
- C++ if else 語句
- C++ 巢狀 if 語句
- C++ switch 語句
- C++ 巢狀 switch 語句
- C++ 迴圈型別
- C++ while 迴圈
- C++ for 迴圈
- C++ do while 迴圈
- C++ foreach 迴圈
- C++ 巢狀迴圈
- C++ break 語句
- C++ continue 語句
- C++ goto 語句
- C++ 建構函式
- C++ 建構函式和解構函式
- C++ 複製建構函式
- C++ 檔案處理
- C++ 檔案和流
- C++ 從檔案中讀取
C++ 中的類成員訪問運算子 (->) 過載
類成員訪問運算子 (->) 可以過載,但這比較棘手。它的定義是為了賦予類型別“類似指標”的行為。-> 運算子必須是成員函式。如果使用,它的返回型別必須是指標或可以應用於其上的類的物件。
-> 運算子經常與指標解引用運算子 * 一起使用來實現“智慧指標”。這些指標是行為類似於普通指標的物件,但它們會在您透過它們訪問物件時執行其他任務,例如在指標被銷燬時或指標用於指向另一個物件時自動刪除物件。
解引用運算子 -> 可以定義為一元后綴運算子。也就是說,給定一個類 -
class Ptr { //... X * operator->(); };
類 **Ptr** 的物件可以用來訪問類 **X** 的成員,其方式與使用指標非常相似。例如 -
void f(Ptr p ) { p->m = 10 ; // (p.operator->())->m = 10 }
語句 p->m 被解釋為 (p.operator->())->m。使用相同的概念,以下示例解釋瞭如何過載類訪問運算子 ->。
#include <iostream> #include <vector> using namespace std; // Consider an actual class. class Obj { static int i, j; public: void f() const { cout << i++ << endl; } void g() const { cout << j++ << endl; } }; // Static member definitions: int Obj::i = 10; int Obj::j = 12; // Implement a container for the above class class ObjContainer { vector<Obj*> a; public: void add(Obj* obj) { a.push_back(obj); // call vector's standard method. } friend class SmartPointer; }; // implement smart pointer to access member of Obj class. class SmartPointer { ObjContainer oc; int index; public: SmartPointer(ObjContainer& objc) { oc = objc; index = 0; } // Return value indicates end of list: bool operator++() { // Prefix version if(index >= oc.a.size()) return false; if(oc.a[++index] == 0) return false; return true; } bool operator++(int) { // Postfix version return operator++(); } // overload operator-> Obj* operator->() const { if(!oc.a[index]) { cout << "Zero value"; return (Obj*)0; } return oc.a[index]; } }; int main() { const int sz = 10; Obj o[sz]; ObjContainer oc; for(int i = 0; i < sz; i++) { oc.add(&o[i]); } SmartPointer sp(oc); // Create an iterator do { sp->f(); // smart pointer call sp->g(); } while(sp++); return 0; }
當編譯並執行上述程式碼時,會產生以下結果:
10 12 11 13 12 14 13 15 14 16 15 17 16 18 17 19 18 20 19 21
cpp_overloading.htm
廣告