使用友元函数遍历另一个 class 的私有成员

iterating through private member of another class using friend function

我在下面class声明了一个友元函数。

Class 型号

#include "fileio.h"
class fileio;
class model
{
    std::vector<element>m_elements;
    public:
    friend void fileio::element_iterator();
}

element_iterator()class fileio.

的 public 函数

Class 文件

#include "model.h"
class model;
class fileio
{     
    model* m_model;
    public:
    fileio(model*);
    void element_iterator();
}

element_iterator()函数定义如下

void fileio::element_iterator()
{
    for(auto &iter : m_model->m_elements)
    {
        //some functions
    }
}

我想使用友元函数从另一个 class 迭代 m_elements。但我收到如下错误:

错误:

 model.h : error: invalid use of incomplete type 'class fileio'
 friend void fileio::read_boundary();

 model.h : error: forward declaration of 'class fileio'
 class fileio; 

 modell.h : In member function 'void fileio::read_boundary()':

 cmodel.h : error: 'std::vector<element> model::m_elements' is private
 std::vector<element>m_elements;

 fileio.cpp: error: within this context
 for(auto iter:m_model->m_elements)

编辑:
在 fileio.h 中没有前向声明 class model 会给出另一组错误,如下所示:

error: 'model' has not been declared
 fileio(model*); 

 error: 'model' does not name a type     
      model* m_model;

 candidates are:
     fileio::fileio(int*)
     fileio(model*);
      no known conversion for argument 2 from 'model*' to 'int*'

如果我注释掉友元函数声明及其定义,那么程序将运行没有错误。 我该如何解决?

而不是 forward-declaring fileiomodel.h 中包括它的完整定义。

// fileio.h
class model;
class fileio
{
    model* m_model;
    public:
    void element_iterator();
};

// model.h
#include "fileio.h"
class model
{
    std::vector<int >m_elements;
    public:
    friend void fileio::element_iterator();
};

wandbox example


或者,您可以将整个 fileio class 设为 friend - 这样您就可以使用其 forward-declaration, 这可能是你想要的,这取决于你的实际情况。

// model.h
class fileio;
class model
{
    std::vector<int >m_elements;
    public:
    friend class fileio;
};

// fileio.h
class model;
class fileio
{
    model* m_model;
    public:
    void element_iterator();
};

wandbox example