两次调用 -> 操作符

来源:互联网 发布:最新地区数据库 编辑:程序博客网 时间:2024/04/29 07:46

#include <stdio.h>

template<class T>
class CallProxy
{
public:
    CallProxy(T* apT) :
        mpT(apT)
    {
        
// nothing to do

    }

    T* operator->() const
    {
        return mpT;
    }
private:
    T* mpT;
/// Member pointer of the accessed class

};

template<class T>
class Wrap
{
public:
    explicit Wrap(T& arT) :
        mpT(&arT)
    {
        
// nothing to do

    }

   CallProxy<T>    operator->()
    {

        return CallProxy<T>(mpT);
    }
private:
    T* mpT;
/// member pointer to the wrapped class

};

template<class T>
class Shared : public Wrap<T>
{
public:
    explicit Shared(T& arT) :
        Wrap<T>(arT)
    {
        
// nothing to do

    }
};

class BcmRegistry
{
public:
    void show()
    {
        printf("test..../n");
    }
};

Shared<BcmRegistry>& theConfig()
{
    static BcmRegistry theRegistry;
    static Shared<BcmRegistry> threadSafe(theRegistry);

    return threadSafe;
}

void main()
{
    theConfig()->show();
}

从我单步调试结果来说,我也知道是这样...
从结果推断出来了, 但并没有理解, 不知道有没有资料上介绍了这个.

另外:
      theConfig()->show();和
    theConfig().operator ->()->show();和
    theConfig().operator ->().operator ->()->show();
具有相同效果. 第三种方式很让人明白. 估计这只是直接调用成员函数,而不算是重载?
而且operator不能去掉.

    另外,我将theConfig()函数的返回值改成指针类型,那么只有
        theConfig()->operator ->()->show();和
        theConfig()->operator ->().operator ->()->show();
    两种可行.

   由此,我认为, 在->运算时: 先判断->左边值的类型 是否有重载的->,若有则调用, 并将返回值放在->的左侧,并继续先前步骤, 直到没有了重载的, 就执行正常的->运算

该问题出处:http://bbs3.chinaunix.net/viewthread.php?tid=1492138&pid=10800209&page=1&extra=page%3D1#pid10800209

原创粉丝点击