C++類中的友元函數(shù)[1]

簡介

本文要解決的兩個問題:

  • 什么是友元函數(shù)?
  • 如何定義友元函數(shù)?

什么是友元函數(shù)

類中的成員變量及成員函數(shù)有公有、私有、受保護的概念,當(dāng)一個函數(shù)A不是類的成員函數(shù),但是希望可以訪問類中的非公有成員,此時需要將函數(shù)A聲明為類的友元函數(shù)。

總的來說:

  • 友元函數(shù)并不屬于類的成員函數(shù)
  • 友元函數(shù)可以訪問類的非公共有成員

如何定義友元函數(shù)

如果一個類希望把一個函數(shù)作為自己的友元函數(shù),只需要增加一條以friend關(guān)鍵字開始的函數(shù)聲明語句

例程

#include <iostream>
#include <string>

class Book
{
public:
    friend void friendPrint(Book& bk); //聲明friendPrint為Book類的友元函數(shù)
    Book(std::string& title,unsigned int price)
        :bookTitle(title),bookPrice(price){}
    std::string getTitle(void) const
    {
        return bookTitle;
    }
    unsigned int getPrice(void) const
    {
        return bookPrice;
    }
private:
    std::string bookTitle;
    unsigned int bookPrice;
};
void friendPrint(Book& bk)
{
    std::cout << "friend function:-------" << "\n";
    //注意這里訪問Book::bookTitle與Book::bookPrice的方式
    //它們都是私有成員哦
    std::cout << "bookTitle:" <<bk.bookTitle  << "\n"
        << "boolPrice:" << bk.bookPrice << "\n";
}
void unfriendPrint(Book& bk)
{
    std::cout << "unfriend function:--------" << "\n";
    std::cout << "bookTitle:" << bk.getTitle() << "\n"
        << "boolPrice:" << bk.getPrice() << "\n";
}

int main()
{
    Book bk(std::string("C++ Primer"), 88);
    unfriendPrint(bk);
    friendPrint(bk);
    return 0;
}
//輸出結(jié)果:
unfriend function:--------
bookTitle:C++ Primer
boolPrice:88
friend function:-------
bookTitle:C++ Primer
boolPrice:88

注意事項

  • 友元函數(shù)的聲明是用于指定某個函數(shù)對于類的訪問權(quán)限,并不是通常意義上的函數(shù)聲明,所以我們需要在類外針對該函數(shù)再次聲明
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容