问题
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?
回答1:
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 of class test
.
The declaration friend void friendly_function();
must be inside the test class however, as this tells the compiler that friendly_function()
is allowed access to the private members of test
.
Since friendly_function()
is not a member of class 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.
namespace test_ns {
class test
{
public:
friend void friendly_function(test &_t);
friend bool operator<(const test& _lhs, const test& _rhs);
private:
int data;
}; // class test
void friendly_function(test &_t)
{
_t.data = 0;
}
bool operator<(const test& _lhs, const test& _rhs)
{
return _lhs.data < _rhs.data;
}
} // namespace test_ns
That should solve the problem. Friend functions are kind of subtle in that they may look like member functions, but actually aren't!
来源:https://stackoverflow.com/questions/18520626/friend-function-of-class-produces-error-no-member-function-declared