フレンドクラス・friend

スポンサーリンク
スポンサーリンク
ライフスタイル関連のコンテンツ
お金 | 仕事 | 勉強 | プライベート | 健康 |
プログラミング関連のコンテンツ
C言語/C++入門 | Ruby入門 | Python入門 | プログラミング全般

フレンド関数について解説しましたが、firend宣言は、関数だけでなくクラスにも利用できます。

スポンサーリンク

あるクラス(クラスAとします)の中で、別のクラス(クラスBとします)をfriend宣言すると、クラスBが、クラスAのメンバにアクセスできるようになります。
private宣言されたメンバも含み、アクセス指定子に関係なくアクセス可能となります。

#include <iostream>
 
class parent {
    private:
        int years;    // 年
        int month;    // 月
    public:
        // 年と月をセット
        void set(const int y, const int m) {
            years = y;
            month = m;
        }
 
    // フレンドする
    friend class child;
};
 
class child {
    public:
        void display(const parent obj) {
            std::cout << "years : " << obj.years << "\n";
            std::cout << "month : " << obj.month << "\n";
        }
};
 
// テストルーチン
int main() {
    class parent a_parent;
    a_parent.set(2008, 6);
 
    class child a_child;
    a_child.display(a_parent);
 
    return 0;
}

実行結果。

years : 2008
month : 6

friend 宣言がないと、「private メンバ (クラス ‘parent’ で宣言されている) にアクセスできません。」と、コンパイルエラーが起こります。

スポンサーリンク
 
スポンサーリンク