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;
// 假設一個實際的類
class Obj {
static int i, j;
public:
void f() const { cout << i++ << endl; }
void g() const { cout << j++ << endl; }
};
// 靜態成員定義
int Obj::i = 10;
int Obj::j = 12;
// 為上面的類實現一個容器
class ObjContainer {
vector<Obj*> a;
public:
void add(Obj* obj)
{
a.push_back(obj); // 調用向量的標準方法
}
friend class SmartPointer;
};
// 實現智能指針,用於訪問類 Obj 的成員
class SmartPointer {
ObjContainer oc;
int index;
public:
SmartPointer(ObjContainer& objc)
{
oc = objc;
index = 0;
}
// 返回值表示列表結束
bool operator++() // 首碼版本
{
if(index >= oc.a.size() - 1) return false;
if(oc.a[++index] == 0) return false;
return true;
}
bool operator++(int) // 尾碼版本
{
return 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); // 創建一個迭代器
do {
sp->f(); // 智能指針調用
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