Cplusplus-cpp-friend-functions

提供:Dev Guides
移動先:案内検索

C ++フレンド関数

クラスのフレンド関数は、そのクラスのスコープ外で定義されますが、クラスのすべてのプライベートおよび保護されたメンバーにアクセスする権利があります。 フレンド関数のプロトタイプはクラス定義に表示されますが、フレンドはメンバー関数ではありません。

フレンドは、関数、関数テンプレート、メンバー関数、またはクラスまたはクラステンプレートにすることができます。この場合、クラス全体とそのメンバー全員がフレンドになります。

関数をクラスのフレンドとして宣言するには、次のようにキーワード friend をクラス定義の関数プロトタイプの前に置きます-

class Box {
   double width;

   public:
      double length;
      friend void printWidth( Box box );
      void setWidth( double wid );
};

クラスClassOneのフレンドとしてクラスClassTwoのすべてのメンバー関数を宣言するには、クラスClassOneの定義に次の宣言を配置します-

friend class ClassTwo;

次のプログラムを検討してください-

#include <iostream>

using namespace std;

class Box {
   double width;

   public:
      friend void printWidth( Box box );
      void setWidth( double wid );
};

//Member function definition
void Box::setWidth( double wid ) {
   width = wid;
}

//Note: printWidth() is not a member function of any class.
void printWidth( Box box ) {
  /*Because printWidth() is a friend of Box, it can
   directly access any member of this class*/
   cout << "Width of box : " << box.width <<endl;
}

//Main function for the program
int main() {
   Box box;

  //set box width without member function
   box.setWidth(10.0);

  //Use friend function to print the wdith.
   printWidth( box );

   return 0;
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Width of box : 10