【問題】所有的「友誼函式」,都可以被設計成「成員函式」嗎?


Recommended Posts

請問 在C++裡面所有的「友誼函式」,都可以被設計成「成員函式」嗎???

基本上,是的!!!

但是有時候friend還蠻好用的說

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 called publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas.

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).

Onto the answer;

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.

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
{
friend class Mother;

public:

string name( void );

protected:

void setName( string newName );
};

在用google的時候多查一查英文資料可以學到更多東西。

鏈接文章
分享到其他網站

請登入後來留意見

在登入之後,您才能留意見



立即登入