为什么这个好友函数不能访问类的私有成员? [英] Why this friend function can't access a private member of the class?

查看:180
本文介绍了为什么这个好友函数不能访问类的私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从 extractHistogram() GHistogram 类的bins私有成员时,会收到以下错误$ c> implementation:

I am getting the following error when I try to access bins private member of the GHistogram class from within the extractHistogram() implementation:

error: 'QVector<double> MyNamespace::GHistogram::bins' is private
error: within this context

'in this context'错误指向 extractHistogram()实现。有没有人知道我的朋友函数声明有什么问题?

Where the 'within this context' error points to the extractHistogram() implementation. Does anyone knows what's wrong with my friend function declaration?

这里是代码:

namespace MyNamespace{

class GHistogram
{

public:
    GHistogram(qint32 numberOfBins);
    qint32 getNumberOfBins();

    /**
     * Returns the frequency of the value i.
     */
    double getValueAt(qint32 i);
    friend GHistogram * MyNamespace::extractHistogram(GImage *image, 
                                                      qint32 numberOfBins);

private:
    QVector<double> bins;
};

GHistogram * extractHistogram(GImage * image, 
                              qint32 numberOfBins);

} // End of MyNamespace


推荐答案

根据我的GCC,上面的代码不编译,因为 extractHistogram()的声明出现在类定义后,它是 friend ed。编译器扼杀了 friend 语句,说 extractHistogram 既不是函数也不是数据成员。所有的工作以及 bins 是可访问的,当我将声明移动到类定义之前(并添加一个前进声明 class GHistogram; 使得返回类型为编译器所知)。当然, extractHistogram()的代码应该写在命名空间内,可以通过

According to my GCC the above code does not compile because the declaration of extractHistogram() appears after the class definition in which it is friended. The compiler chokes on the friend statement, saying that extractHistogram is neither a function nor a data member. All works well and bins is accessible when I move the declaration to before the class definition (and add a forward declaration class GHistogram; so that the return type is known to the compiler). Of course the code for extractHistogram() should be written inside the namespace, either by

namesapce MyNameSpace {
// write the function here
}

GHistogram *MyNameSpace::extractHistogram( //....

这篇关于为什么这个好友函数不能访问类的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆