C++友元類

2628 ワード

1.いつ友元類を使いますか.
クラスが別のクラスのプライベートメンバーにアクセスできるようにする場合は、クラスを別のクラスの友元クラスとして宣言します.
2.友元類作用?
友元クラスのすべてのメソッドは、別のクラスの友元関数であり、友元クラスは別のクラスのすべてのメンバー(プライベートメンバーと保護メンバーを含む)にアクセスできます.
3.友元クラスの構文フォーマット:friend classクラス名;
4.友元類の特徴
1)友元関係は継承できない.
2)友元関係は一方的である.
3)友元関係は伝達性を持たない.
5.友元クラスの一例
#include <iostream>
using namespace std;
class TV 
{
    public:
      friend class Tele;//   
      TV():on_off(off),volume(20),channel(3),mode(tv){}
    private:    
      enum{on,off};
      enum{tv,av};
      enum{minve,maxve=100};
      enum{mincl,maxcl=60};
      bool on_off;
      int  volume;
      int channel;
      int mode;
};
class Tele
{//       TV     ,      
    public:
       void OnOFF(TV&t){t.on_off=(t.on_off==t.on)?t.off:t.on;}
       void SetMode(TV&t){t.mode=(t.mode==t.tv)?t.av:t.tv;}
       bool VolumeUp(TV&t);
       bool VolumeDown(TV&t);
       bool ChannelUp(TV&t);
       bool ChannelDown(TV&t);
       void show(TV&t)const;    
};
bool Tele::VolumeUp(TV&t)
{
    if (t.volume<t.maxve)
    {
        t.volume++;
        return true;
    } 
    else
    {
        return false;
    }
}
bool Tele::VolumeDown(TV&t)
{
    if (t.volume>t.minve)
    {
        t.volume--;
        return true;
    } 
    else
    {
        return false;
    }
}
bool Tele::ChannelUp(TV&t)
{
    if (t.channel<t.maxcl)
    {
        t.channel++;
        return true;
    } 
    else
    {
        return false;
    }
}
bool Tele::ChannelDown(TV&t)
{
    if (t.channel>t.mincl)
    {
        t.channel--;
        return true;
    } 
    else
    {
        return false;
    }
}
void Tele::show(TV&t)const
{
    if (t.on_off==t.on)
    {
        cout<<"    "<<(t.on_off==t.on?"  ":"  ")<<endl;
        cout<<"     :"<<t.volume<<endl;
        cout<<"       :"<<(t.mode==t.av?"AV":"TV")<<endl;
        cout<<"   :"<<t.channel<<endl;
 
    } 
    else
    {
        cout<<"    "<<(t.on_off==t.on?"  ":"  ")<<endl;
    }
     
}
int main()
{
    Tele t1;
    TV t2;
    t1.show(t2);
    t1.OnOFF(t2);
    t1.show(t2);
    cout<<"    "<<endl;
    t1.VolumeUp(t2);
    cout<<"  +1"<<endl;
    t1.ChannelUp(t2);
    cout<<"    "<<endl;
    t1.SetMode(t2);
    t1.show(t2);
    return 0;
}

プログラムの6行目でTVテレビ類の友元類Teleを定義した.では、プログラムではTVクラスのプライベートメンバーを呼び出すことができます.次に、プログラムの出力を示します.