Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this friend function can't access a private member of the class?

Tags:

c++

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

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

Here's the code:

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
like image 835
Alceu Costa Avatar asked Mar 23 '10 14:03

Alceu Costa


1 Answers

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
}

or

GHistogram *MyNameSpace::extractHistogram( //....
like image 72
Ari Avatar answered Nov 14 '22 23:11

Ari