前景提要C++中,内部类可以访问外部内的私有变量和函数,只不过需要先引入外部类的对象。
class A{
private:
int a;
int b;
class InnerA{
int inner_a;
int inner_b;
InnerA(A* objA){
inner_a = objA->a;
inner_b = objA->b;
}
};
};
迭代器:提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。
Iterator.h
#ifndef ITERATOR_H_
#define ITERATOR_H_
#include<iostream>
using namespace std;
/**
* 迭代器抽象接口
*
*/
class Iterator{
public:
virtual bool hasNext() = 0;
virtual int next() = 0;
virtual ~Iterator(){}
};
#endif
Container.h
#ifndef CONTAINER_H_
#define CONTAINER_H_
#include<iostream>
using namespace std;
#include<vector>
#include "Iterator.h"
/**
* 容器抽象类
*/
class Container{
public:
virtual Iterator* getIterator() = 0;
virtual ~Container(){}
};
#endif
MyCon.h
class MyCon : public Container{
private:
int* start;
int* tail;
int* end;
public:
MyCon(){
start = new int[100];
tail = start;
}
// 获取迭代器
Iterator* getIterator(){
return new MyIterator(this);
}
// 添加元素
void push_back(int& value){
*tail = value;
tail++;
}
~MyCon(){
delete[] start;
}
protected:
class MyIterator : public Iterator{
public:
int* inner_start;
int* inner_tail;
MyIterator(MyCon* mycon){
inner_start = mycon->start;
inner_tail = mycon->tail;
}
virtual bool hasNext(){
if(inner_start < inner_tail){
return true;
}
return false;
}
virtual int next(){
int cur = *inner_start;
inner_start++;
return cur;
}
};
};
main.cpp
#include<iostream>
using namespace std;
#include "Container.h"
int main(){
MyCon mycon;
int a = 1;
mycon.push_back(a);
a = 2;
mycon.push_back(a);
a = 3;
mycon.push_back(a);
Iterator* itr = mycon.getIterator();
while(itr->hasNext()){
cout << itr->next() << endl;
}
return 0;
}
网站推荐:迭代器模式 | 菜鸟教程https://www.runoob.com/design-pattern/iterator-pattern.html
|