标签:style blog color os io strong cti div
这里以一个智能指针类为例,智能指针所指为一个对象。
而事实上,STL迭代器的开发均需要重载这两个操作符,上一篇文章分析STL 迭代器中除了要用到template技巧外,还需要重载技巧
1 #include<iostream> 2 using namespace std; 3 class Screen 4 { 5 6 public: 7 friend ostream& operator<<(ostream&os, Screen &s); 8 int action(){ return ++data; } 9 Screen(int i = 0) :data(i){} 10 private: 11 int data; 12 }; 13 ostream& operator<<(ostream&os, Screen &s) 14 { 15 os << s.data; 16 return os; 17 } 18 class U_ptr 19 { 20 friend class ScreenPtr; 21 Screen* p; 22 size_t use; 23 U_ptr(Screen *pp) :p(pp), use(1){} 24 ~U_ptr(){ delete p; } 25 }; 26 class ScreenPtr 27 { 28 private: 29 U_ptr *ptr; 30 public: 31 ScreenPtr(Screen *p) :ptr(new U_ptr(p)){} 32 ScreenPtr(ScreenPtr &orgi_p) :ptr(orgi_p.ptr){ ++ptr->use; } 33 ~ScreenPtr(){ if (--ptr->use == 0)delete ptr; } 34 Screen& operator*() 35 { 36 return *(ptr->p); 37 } 38 Screen* operator->() 39 { 40 return ptr->p; 41 } 42 }; 43 class gao 44 { 45 private: 46 ScreenPtr *p; 47 public: 48 gao(ScreenPtr* q) :p(q){} 49 ScreenPtr& operator->() 50 { 51 return *p; 52 } 53 }; 54 int main() 55 { 56 57 ScreenPtr ptr(new Screen(5)); 58 cout << "*操作符 " << *ptr << endl; 59 cout << "->操作符 " << ptr->action() << endl; 60 ScreenPtr* pp = &ptr; 61 gao d(pp); 62 cout << "!" << d->action() << endl; 63 system("pause"); 64 }
关于解引用*和箭头操作符->的重载,布布扣,bubuko.com
标签:style blog color os io strong cti div
原文地址:http://www.cnblogs.com/gaoduan/p/3903500.html