問題描述
我一直在閱讀 C++ FAQ 并且對 friend
聲明.我個(gè)人從未使用過它,但我對探索該語言很感興趣.
I have been reading through the C++ FAQ and was curious about the friend
declaration. I personally have never used it, however I am interested in exploring the language.
使用 friend
的好例子是什么?
What is a good example of using friend
?
閱讀 FAQ 多一點(diǎn)我喜歡 <<
>>
運(yùn)算符重載和添加為這些類的朋友的想法.但是我不確定這不會破壞封裝.這些異常什么時(shí)候才能保持在 OOP 的嚴(yán)格范圍內(nèi)?
Reading the FAQ a bit longer I like the idea of the <<
>>
operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?
推薦答案
首先 (IMO) 不要聽那些說 friend
沒有用的人.它是有益的.在許多情況下,您將擁有不打算公開提供的數(shù)據(jù)或功能的對象.對于具有許多作者的大型代碼庫尤其如此,他們可能只是表面上熟悉不同領(lǐng)域.
Firstly (IMO) don't listen to people who say friend
is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas.
友元說明符有多種替代方案,但它們通常很麻煩(cpp 級別的具體類/屏蔽類型定義)或不是萬無一失的(注釋或函數(shù)名稱約定).
There ARE alternatives to the friend specifier, but often they are cumbersome (cpp-level concrete classes/masked typedefs) or not foolproof (comments or function name conventions).
進(jìn)入答案;
friend
說明符允許指定的類訪問受保護(hù)的數(shù)據(jù)或在發(fā)出友元語句的類中的功能.例如在下面的代碼中,任何人都可以向孩子詢問他們的名字,但只有母親和孩子可以更改名字.
The friend
specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name.
您可以通過考慮更復(fù)雜的類(例如 Window)來進(jìn)一步了解這個(gè)簡單的示例.一個(gè) Window 很可能有許多不應(yīng)公開訪問的函數(shù)/數(shù)據(jù)元素,但相關(guān)類(例如 WindowManager)需要這些元素.
You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager.
class Child
{
//Mother class members can access the private parts of class Child.
friend class Mother;
public:
string name( void );
protected:
void setName( string newName );
};
這篇關(guān)于什么時(shí)候應(yīng)該在 C++ 中使用“朋友"?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!