【C++】フレンド関数
フレンド関数の勉強メモです。基本的な使い方についてです。
フレンド関数
C++ではクラスの外部で定義した関数をクラスのprivateメンバにアクセスできるようにすることができます。
そのような関数をフレンド関数と呼びます。friend修飾子を使ってフレンド関数を作ることができます。フレンド関数はクラスのメンバ関数になる訳ではないことに注意。
こんな感じです。
#include<iostream> using namespace std; class myclass { int a, b; // private member public: // コンストラクタ myclass(int i, int j) { a = i; b = j; } // フレンドにする friend int sum(myclass x); }; int sum(myclass x) { return x.a + x.b; } int main() { myclass n(3, 4); cout << sum(n) << endl; return 0; }
実行結果
7
この例ではありがたさがわかりにくいですが、複数のクラスで同様の処理を行う場合などでフレンド関数は効力を発揮します。
次の例ではidle関数が2つのクラスC1、C2のフレンド関数となっています。
#include<iostream> using namespace std; const int IDLE = 0; const int INUSE = 1; class C2; class C1 { int status; public: void set_status(int state); friend int idle(C1 a, C2 b); }; class C2 { int status; public: void set_status(int state); friend int idle(C1 a, C2 b); }; void C1::set_status(int state) { status = state; } void C2::set_status(int state) { status = state; } int idle(C1 a, C2 b) { if (a.status || b.status) return 0; else return 1; } int main() { C1 x; C2 y; x.set_status(IDLE); y.set_status(IDLE); if (idle(x, y)) cout << "Screen Can Be Used.\n"; else cout << "Pop-up In Use.\n"; x.set_status(INUSE); if (idle(x, y)) cout << "Screen Can Be Used.\n"; else cout << "Pop-up In Use.\n"; return 0; }
まとめ
まだfriend関数の恩恵を受けるには至っていないですが、とりあえず使い方はわかったかな、という感じです。 演算子のオーバーロードで役に立つみたいですね。
参考
ハーバート・シルト(2009)「標準講座C++」柏原正三訳・監修 株式会社トップスタジオ