内部类可以访问外部类的private方法。
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class MyList {
public:
MyList(vector<T>* list): v_(list) {
}
class Iterator {
public:
Iterator(MyList* plist): plist_(plist) {
}
T* Next(const T& key) {
return plist_->FindGreaterOrEqual(key);
}
private:
MyList * plist_;
};
Iterator GetIterator() {
return Iterator(this);
}
private:
vector<T>* v_;
T* FindGreaterOrEqual(const T& key) {
for (size_t i = 0; i < v_->size(); i++) {
if ( v_->at(i) < key) {
} else {
return &(v_->at(i));
}
}
return NULL;
}
};
void test() {
int myints[] = {1,2,3,40,50,60,70};
vector<int> va(myints, myints + sizeof(myints)/sizeof(int));
MyList<int> mylist(&va);
int key = 4;
//MyList<int>::Iterator it(&mylist);
MyList<int>::Iterator it = mylist.GetIterator();
int* pa = it.Next(key);
cout << "to find " << key << ", find " << *pa << endl;
}
int main() {
test();
}
C++内部类
最新推荐文章于 2022-07-03 22:38:05 发布