采用如下的方式访问外部类:
// OperatorTest.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<vector>
using namespace std;
class Obj {
static int i, j;
public:
void f() {
cout << "i:" << i++ << endl;
}
void g() {
cout << "j:" << j++ << endl;
}
};
int Obj::i = 11;
int Obj::j = 12;
class ObjContainer {
vector<Obj*> objs;
public:
class SmartPointer;
friend class SmartPointer;
void add(Obj* obj) {
objs.push_back(obj);
}
class SmartPointer {
ObjContainer& oc;
int index;
public:
SmartPointer(ObjContainer& oc):oc(oc){
index = 0;
}
bool operator++() {
index++;
if (index >=oc.objs.size())return false;
if (oc.objs[index] == 0)return false;
return true;
}
bool operator++(int) {
return operator++();
}
Obj* operator->() {
return oc.objs[index];
}
};
SmartPointer begin() {
return SmartPointer(*this);
}
};
int main()
{
const int sz = 12;
ObjContainer oc;
Obj objs[sz];
ObjContainer::SmartPointer sp = oc.begin();
for (int i = 0; i < sz; i++) {
oc.add(&objs[i]);
}
do {
sp->f();
sp->g();
} while (sp++);
}