クラスのメンバ関数でない、通常のルーチン関数から、クラス内のprivate宣言のメンバにアクセスするには、通常のルーチン関数をfriendキーワードで宣言することが必要です。
クラスは、自分のフレンド関数(friend)を指定することで、クラスの外側の関数が、クラス内のprivateメンバにアクセス可能となります。
以下のfriend_testクラスでは、ルーチンのdisplay(const friend_test& obj)を、friend宣言しています。
これにより、display(const friend_test& obj)は、friend_testクラスのprivateメンバである、years, monthのデータにアクセス可能となります。
#include <iostream>
class friend_test {
private:
int years; // 年
int month; // 月
public:
// 年と月をセット
void set(const int y, const int m);
// フレンドする
friend void display(const friend_test& obj);
};
// 年と月をセットするメンバ関数
inline void friend_test::set(const int y, const int m) {
years = y;
month = m;
}
// 年と月を表示するルーチン
void display(const friend_test& obj) {
std::cout << "years : " << obj.years << "\n";
std::cout << "month : " << obj.month << "\n";
}
// メインルーチン
int main() {
// オブジェクト生成
class friend_test a_friend;
// 年月をセット
a_friend.set(2008, 6);
// 年月を表示
display(a_friend);
return 0;
}
実行結果。
years : 2008 month : 6
もし、friendキーワードがなかったら、「privateメンバにアクセスできません。」とコンパイルエラーが起こります。
■この記事のトラックバックURL:
http://www.mapee.jp/mpe334/mt-tb.cgi/243