Ray's playground

 

Hiding the Implementation(Chapter 5 of Thinking in C++)

NestFriend.cpp
  1 #include <iostream>
  2 #include <cstring>
  3 using namespace std;
  4 const int sz = 20;
  5 
  6 struct Holder
  7 {
  8     private:
  9         int a[sz];
 10     public:
 11         void initialize();
 12         struct Pointer;
 13         friend Pointer;
 14         struct Pointer
 15         {
 16             private:
 17                 Holder* h;
 18                 int* p;
 19             public:
 20                 void initialize(Holder* h);
 21                 void next();
 22                 void previous();
 23                 void top();
 24                 void end();
 25                 int read();
 26                 void set(int i);
 27         };
 28 };
 29 
 30 void Holder::initialize()
 31 {
 32     memset(a, 0, sz * sizeof(int));
 33 }
 34 
 35 void Holder::Pointer::initialize(Holder* rv)
 36 {
 37     h = rv;
 38     p = rv->a;
 39 }
 40 
 41 void Holder::Pointer::next()
 42 {
 43     if(p < &(h->a[sz-1]))
 44     {
 45         p++;
 46     }
 47 }
 48 
 49 void Holder::Pointer::previous()
 50 {
 51     if(p > &(h->a[0]))
 52     {
 53         p--;
 54     }
 55 }
 56 void Holder::Pointer::top()
 57 {
 58     p = &(h->a[0]);
 59 }
 60 
 61 void Holder::Pointer::end()
 62 {
 63     p = &(h->a[sz-1]);
 64 }
 65 
 66 int Holder::Pointer::read()
 67 {
 68     return *p;
 69 }
 70 
 71 void Holder::Pointer::set(int i)
 72 {
 73     *= i;
 74 }
 75 
 76 int main()
 77 {
 78     Holder h;
 79     Holder::Pointer  hp, hp2;
 80     int i;
 81 
 82     h.initialize();
 83     hp.initialize(&h);
 84     hp2.initialize(&h);
 85     for(i=0; i<sz; i++)
 86     {
 87         hp.set(i);
 88         hp.next();
 89     }
 90 
 91     hp.top();
 92     hp2.end();
 93     for(i = 0; i < sz; i++)
 94     {
 95         cout << "hp = " << hp.read() 
 96             << ", hp2 = " << hp2.read() << endl;
 97         hp.next();
 98         hp2.previous();
 99     }
100 
101     cin.get();
102 }

 

posted on 2010-11-10 20:38  Ray Z  阅读(247)  评论(0编辑  收藏  举报

导航