I have a class, and I am trying to create a friend function to operate on the data of that class.
Here is an example of what I am trying to do:
// test.hpp
class test
{
public:
friend void friendly_function();
private:
int data;
};
void test::friendly_function()
{
data = 0;
}
However, the compiler spits out an error: test.hpp:23:34: error: no ‘void test::friendly_function()’ member function declared in class ‘test’
I know I can declare operators in this way, like so:
class test
{
public:
friend const bool operator<(const test& _lhs, const test& _rhs);
private:
int data;
};
const bool test::operator<(const test& _lhs, const test& _rhs)
{
return (_lhs.data < _rhs.data);
}
So why can't I do this with friendly_function
? Are friend functions only allowed as operators?
I actually managed to figure out the problem before I posted this question, so it seemed sensible to give the answer, as other people might find it useful in future. I have also set the answer to "community wiki", so other people can improve it if they wish.
The problem is that the friend functions are not members of the class, and therefore must be coded without the
test::
specifier, since they are not members ofclass test
.The declaration
friend void friendly_function();
must be inside the test class however, as this tells the compiler thatfriendly_function()
is allowed access to the private members oftest
.Since
friendly_function()
is not a member ofclass test
, it would be a good idea to put all this code together in a namespace, which will group all the functions and classes inside one logical block.That should solve the problem. Friend functions are kind of subtle in that they may look like member functions, but actually aren't!