箭头重载符的学问

The arrow operator has no inputs. Technically, it can return whatever you want, but it should return something that either is a pointer or can become a pointer through chained -> operators.

The -> operator automatically dereferences its return value before calling its argument using the built-in pointer dereference, not operator*, so you could have the following class:

class PointerToString
{
    string a;

  public:
    class PtPtS
    {
      public:
        PtPtS(PointerToString &s) : r(s) {}
        string* operator->()
        {
           std::cout << "indirect arrow";
           return &*r;
        }
      private:
        PointerToString &r;
    };

    PointerToString(const string &s) : a(s) {}
    PtPts operator->() const
    {
        std::cout << "arrow dereference\n"; 
        return *this;
    }
    string &operator*() const
    {
        std::cout << "dereference\n";
        return a;
    }
};

Use it like:

PointerToString ptr(string("hello"));
string::size_type size = ptr->size();

which is converted by the compiler into:

string::size_type size = (*ptr.operator->().operator->()).size();

(with as many .operator->() as necessary to return a real pointer) and should output

arrow dereference
indirect dereference
dereference

Note, however, that you can do the following:

PointerToString::PtPtS ptr2 = ptr.operator->();

///
class PointerToString
{
	string a;


public:
	class PtPtS
	{
	public:
		PtPtS(PointerToString& s) : r(s) {}
		string* operator->()
		{
			std::cout << "indirect arrow\n";
			return &*r;
		}
	private:
		PointerToString &r;
	};


	PointerToString(const string &s) : a(s) {}
	PtPtS operator->() 
	{
		std::cout << "arrow dereference\n";
		return *this;
	}
	string &operator*()
	{
		std::cout << "dereference\n";
		return a;
	}
};
PointerToString ptr(string("hello"));
	string::size_type size = ptr->size();


	//string::size_type size = (*ptr->()->())->size();
	string::size_type size1 = (*ptr.operator->().operator->()).size();
	string::size_type size2 = (ptr.operator->().operator->())->size();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值