1
4

1 回答 1

2

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!

于 2013-08-29T20:43:47.080 回答