一、friend class的概念
C++中的friend關鍵字用於在類定義中聲明其他類或函數為友元,這樣它們就可以訪問類的私有成員。而friend class則用於聲明一整個類為友元。
當一個類被聲明為另一個類的友元時,它可以訪問該類的私有成員,但並不具備該類的成員函數或方法。而當一個類被聲明為另一個類的friend class時,它可以訪問該類的私有成員和成員函數或方法。
二、friend class的使用場景
friend class的使用場景多種多樣,下面介紹其中兩種典型的情境。
1.友元類與封裝的關係:
class Box { private: int length; int width; int height; public: Box(int l = 0, int w = 0, int h = 0) { length = l; width = w; height = h; } friend class BoxVolume; // 聲明BoxVolume類為Box的友元類 }; class BoxVolume { public: int getVolume(Box &box) { return box.length * box.width * box.height; } };
在上面的示例中,我們聲明BoxVolume類為Box類的友元類,這樣BoxVolume類就可以訪問Box類的私有成員length、width和height,並利用它們計算出Box的體積。
2.友元類與繼承的關係:
class Fruit { protected: // 注意這裡使用protected而不是private int weight; public: Fruit(int w) : weight(w) {} void showWeight() { std::cout << "Fruit's weight is: " << weight << std::endl; } friend class Apple; // 聲明Apple類為Fruit的友元類 }; class Apple : public Fruit { public: Apple(int w) : Fruit(w) {} void showWeight() { std::cout << "Apple's weight is: " << weight << std::endl; } void showFruitWeight(Fruit &fruit) { std::cout << "Fruit's weight is: " << fruit.weight << std::endl; } };
在上面的示例中,我們聲明Apple類為Fruit類的友元類,這樣Apple類就可以訪問Fruit類的受保護成員weight,並將其作為Apple類自己的成員使用。
三、friend class的優缺點
friend class的優點在於它可以加強類與類之間的關係,提供更為靈活的訪問權限控制。在某些場景下,如上面兩個示例所示,friend class可以極大地簡化類的實現過程,提高程序的執行效率。
然而,friend class也存在缺點。首先,它破壞了面向對象的封裝性,讓友元類得以在類內直接訪問另一個類的私有成員和方法,導致程序難以維護和拓展。其次,使用friend關鍵字增加了代碼複雜度,需要更多的注釋和說明。
四、總結
friend class是C++面向對象編程中一個非常有用的概念,可以提高程序的執行效率和靈活性,但也需要注意封裝性及代碼複雜度。在使用friend class時,需要對其使用的場景和影響進行合理的權衡和把握。
原創文章,作者:AQZO,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/145640.html