迭代器模式 - 循环引用

时间:2014-07-04 01:35:26

标签: c++ iterator circular-dependency

无论如何都要避免这个循环引用?我不能使用foward声明,因为我在PositionBlockIterator中访问PositionBlock的方法......

我知道我可以为PositionBlock创建一个接口,然后在PositionBlockIterator(多态)中使用它。但还有另一种方式吗?

class PositionBlockIterator{
private:
   PositionBlock *posBlock;
public:
     PositionBlockIterator(PositionBlock *posBlock_){
         posBlock = posBlock_;
     }
     /* functions to iterate over positionblock, using posBlock->... */
}

class PositionBlock
{
public:
   PositionBlockIterator * createIterator(){
       return PositionBlockIterator(this);
   }
}

2 个答案:

答案 0 :(得分:1)

class PositionBlock;
class PositionBlockIterator;

class PositionBlockIterator{
    private:
        PositionBlock *posBlock;

    public:
        PositionBlockIterator(PositionBlock *posBlock_);
};

class PositionBlock {
    public:
        PositionBlockIterator * createIterator();
};

PositionBlockIterator::PositionBlockIterator(PositionBlock *posBlock_) {
    posBlock = posBlock_;
}

PositionBlockIterator * PositionBlock::createIterator(){
    return new PositionBlockIterator(this);
}

您还可以看到此编译here。我还建议将两个函数的实现移动到单独的*.cpp文件中。

答案 1 :(得分:1)

嵌套类应该在这种情况下工作(未经测试)。

class PositionBlock{
public:
  class Iterator{
  private:
     PositionBlock *posBlock;
  public:
    Iterator(PositionBlock *posBlock_){
       posBlock = posBlock_;
    }
    /* functions to iterate over positionblock, using posBlock->... */
  };

  Iterator * createIterator(){
     return new Iterator(this);
  }
};