- #include <iostream>
- using namespace std;
- class Object{
- string name,value;
- public:
- void getName(){cout<<name<<endl;}
- void getValue(){cout<<value<<endl;}
- };
- class Container{
- vector vec;
- public:
- void add(Object* obj){
- vec.push_back(obj);
- }
- friend class SmartPointer;
- };
- class SmartPointer{
- Container& container;
- int index;
- public:
- SmartPointer(Container& c):container(c),index(0){}
- bool operator++(){
- if(index>=container.vec.size())
- return false;
- if(container.vec[++index]==NULL)
- return false;
- return true;
- }
- bool operator++(int){
- return operator++();
- }
- Object* operator->() const{
- assert(container.vec[index]!=NULL);
- return container.vec[index];
- }
- };
- void test(){
- Object o[10];
- Container oc;
- for(int i=0;i<10;i++){
- oc.add(&o[i]);
- }
- SmartPointer sp(oc);
- do{
- sp->getName();
- sp->getValue();
- }while(sp++);
- }
Smart Pointer
最新推荐文章于 2023-03-23 09:51:55 发布