类的友元函数产生错误:"未声明'___'成员函数"

Friend Function of Class produces error: "no '___' member function declared"

本文关键字:函数 未声明 成员 友元 错误      更新时间:2023-10-16

我有一个类,我正试图创建一个友元函数来操作该类的数据。

下面是我尝试做的一个例子:

// test.hpp
class test
{
public:
    friend void friendly_function();
private:
    int data;
};
void test::friendly_function()
{
    data = 0;
}

然而,编译器抛出了一个错误:test.hpp:23:34: error: no ‘void test::friendly_function()’ member function declared in class ‘test’

我知道我可以用这种方式声明运算符,比如:

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);
}

那么,为什么我不能用friendly_function来做这件事呢?友元函数是否只允许作为运算符?

实际上,在发布这个问题之前,我已经解决了这个问题,所以给出答案似乎是明智的,因为其他人可能会发现它在未来很有用。我还将答案设置为"社区维基",这样其他人可以根据自己的意愿进行改进。

问题是友元函数不是类的成员,因此必须在没有test::说明符的情况下进行编码,因为它们不是class test的成员。

然而,声明friend void friendly_function();必须在测试类内部,因为这告诉编译器允许friendly_function()访问test的私有成员。

由于friendly_function()不是class test的成员,因此最好将所有这些代码放在一个命名空间中,该命名空间将把所有函数和类分组到一个逻辑块中。

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

这应该能解决问题。Friend函数有点微妙,因为它们看起来可能像成员函数,但实际上不是!