我在下面的类中声明了一个 friend 函数。
类模型
#include "fileio.h"
class fileio;
class model
{
std::vector<element>m_elements;
public:
friend void fileio::element_iterator();
}
element_iterator()
是class fileio
的公共(public)功能。类文件
#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
}
}
我想使用friend函数从另一个类遍历
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*'
如果我注释掉好友函数声明及其定义,则该程序将运行而不会出现错误。
我该如何解决?
最佳答案
而不是在fileio
中向前声明model.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
类设置为friend
-这将允许您使用其前向声明,根据您的实际情况,可能需要使用该声明。// 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