簡體   English   中英

類的Friend Function產生錯誤:“未聲明'___'成員函數”

[英]Friend Function of Class produces error: “no '___' member function declared”

我有一個類,並且我試圖創建一個朋友函數來對該類的數據進行操作。

這是我要執行的操作的一個示例:

// 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做到這一點呢? 是否僅允許將朋友功能用作運算符?

在發布此問題之前,我實際上設法找出了問題所在,因此給出答案似乎很明智,因為其他人將來可能會覺得有用。 我還為“社區Wiki”設置了答案,因此其他人可以根據需要進行改進。

問題在於友元函數不是類的成員,因此必須在沒有test::說明符的情況下進行編碼,因為它們不是class test成員。

聲明friend void friendly_function(); 但是必須在test類中,因為這告訴編譯器允許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

那應該解決問題。 朋友函數有點微妙,因為它們看起來像成員函數,但實際上不是!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM