我已将 >>>
运算符重新定义为 header 中模板类中的友元函数。在其中,我需要调用另一个名为 inputHelper
的函数,我也在 header 中定义了该函数。 (输入助手是递归的)
头文件如下:
template< typename NODETYPE > class Forest
{
/* (other friends) */
friend void inputHelper(istream& file, int previousDepth,
ForestNode<NODETYPE>& previousNode, ForestNode<NODETYPE> *nodeArray,
int nodeCount)
{
/* (dostuff) */
if(someconditional)
{
/* call inputHelper */
}
}
friend istream& operator>>(istream& file, Forest<NODETYPE>& f1)
{
/* (dostuff) */
/* (call inputHelper) */
}
public:
/* ... */
private:
/* ... */
}
但是,在编译时,它显示 |140|error: 'inputHelper' was not declared in this scope|
。您是否必须做一些特别的事情,因为它们都在标题中定义为友元函数?我有点理解 inputHelper
超出了类的范围,但我不确定如何解决这个问题。
最佳答案
友元函数不是成员函数。换句话说,它的范围在你的类的范围之外。通过声明它为友元,你赋予它特殊的权限来访问 Forest 类的 protected 成员,但是你必须访问成员方法的方式应该使用该对象。 MememberMethod() 语法。
在这种情况下,您需要调用 f1.inputHelper(...),而不是直接调用 inputHelper(..)。如果您像这样调用 inputHelper,我想它应该可以正常编译。
关于c++ - 从 C++ header 中定义的友元函数调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4061208/