码迷,mamicode.com
首页 > 其他好文 > 详细

operator ->

时间:2018-12-26 10:29:28      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:inter   follow   std   val   win   str   NPU   before   vat   

 

//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\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.operator->().operator->()).size();

分析这个问题 主要是因为 看stl代码时发现了 auto_ptr 中对其的重载

operator ->

标签:inter   follow   std   val   win   str   NPU   before   vat   

原文地址:https://www.cnblogs.com/jijiboy/p/10177478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!