读《C++ Stragegies and Tacitics》的时候看到了一段很NB的代码,是关于智能指针的 (程序稍作修改,以便在编译器上运行):
1 #include <string>
2 using namespace std;
3
4 class String_ptr {
5 private:
6 string *ptr;
7 public:
8 String_ptr(string *s) : ptr(s) {}
9 string* operator ->() const {return ptr;}
10 operator string*() const {return ptr;}
11 };
12
13 int main(){
14 string s("hello world!");
15 String_ptr sp=&s;
16 int len=sp->length(); //(sp.operator ->())->length();
17 string *dumb_ptr = sp; // sp.operator string *();
18 }
类String_ptr是一个只能指针,用来控制对其所负责的string的访问。其中定义了两个函数 operator->()(用来对string成员函数的访问)和operator string*()(用来进行隐式类型转换的函数)。
我最大的疑问就是为什么operator string()函数没有返回值(返回值应该为 string )?如果函数声明改写为:
string* operator string *() const ;
重新编译就会出错 error: return type specified for 'operator std::string {aka std::basic_string
注意sp的初始化也很不一般:“String_ptr sp=&s;”调用的是String_ptr的构造函数,而不是复制构造函数。
使用模板来实现该智能指针:
1 #include <string>
2 using namespace std;
3
4 template <class T>
5 class Ptr {
6 private:
7 T* ptr;
8 public:
9 Ptr(T* p) : ptr(p) { }
10 T* operator ->() const {return ptr;}
11 operator T*() const {return ptr;}
12 };
13
14 int main(){
15 string s("hello world!");
16 Ptr<string> sp=&s;
17 int len=sp->length();
18 string *dumb_ptr=sp; //sp.operator string *();
19 }
原文链接: https://www.cnblogs.com/wanghetao/archive/2013/05/18/3085680.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/89047
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!