成员访问控制符重载

类成员访问运算符(->)可以被重载,但它比较麻烦它被定义用于为一个类赋予“指针”行为。运算符->必须是一个成员函数。如果使用了->运算符,返回类型必须是指针或者是类的对象。

运算符->通常与指针引用运算符 * 结合使用,用于实现“只能指针”的功能,这些指针是行为与正常指针相似的对象,唯一不同的是,当通过指针访问对象时,他们会执行其他任务。当指针销毁时或者当指针指向另一个对象时,会自动删除对象。

间接引用运算符->可被定义为一个一元后缀运算符,也就是说,给一个类

class Ptr
{
    //
    X * operator->();
}

类Ptr的对象可用于访问类X的成员,使用方法与指针的用法十分类似:

void f(Ptr p)
{
    p -> m = 10; // (p.operator ->()) ->m = 10;
}

语句p -> m 被解释为(p.operator ->()) ->m = 10;

/***
membervis.cpp
***/
#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;
};

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

运行结果:

exbot@ubuntu:~/wangqinghe/C++/20190812$ g++ membervis.cpp -o membervis

exbot@ubuntu:~/wangqinghe/C++/20190812$ ./membervis

10

12

11

13

12

14

13

15

14

16

15

17

16

18

17

19

18

20

19

21

原文地址:https://www.cnblogs.com/wanghao-boke/p/11337850.html