友元函数/友元类

2017-04-19  本文已影响0人  ZayAlan

引入

当某一类或函数需要访问或使用另一类的私有函数或变量时,引入友元。
例如:
你的银行卡号是私有的,别人不能访问,但你父母要往里存钱,此时需要你的银行卡号对其开放访问,这你的父母便是你的友元。

未引入友元的情况

class A{
public:
        ....
private:
        void Func();
        int field;
}

void UseA(A & a)
{
        a field = 5;              //field为对象a中的私有成员,不能访问,报错
}
int main()
{
      A a;
      UseA(a);
}

友元函数的使用方法

格式

friend 被当作友元的函数或类

例如:

class A{
        friend void UseA(A & a);       //声明友元函数
public:
        ....
private:
        void Func();
        int field;
}
void UseA(A & a)
{
        a.field = 5;       //正常访问调用
        ...
}
int main()
{
        A a;
        UseA(a);
}

友元函数和友元类

包括全局函数,和类的成员函数

包括类的全部成员函数

例子如下

class Parent{
public:
        void addMoney(Wallet & w){
        w.money += 8888;
        }
        void checkMoney(Wallet & w){
        cout<<w.history<<endl;
        }
        void checkCourse(Course & c){
        cout<<c.score<<endl;
        }
};
class Wallet{
friend class Parent;      //友元声明一般放在public和private前面
friend void Parent::AddMoney(Wallet &);  //可以只限定Parent类中的特定函数为友元
private:
        int money;
        int history;
}
class A{
friend const A operator + ( const A & Ihs, const A & rhs);
friend void B::f(A&a);
friend class C;
class D;                  //嵌套类
friend class D;        //声明嵌套类为友元,此时class D能够访问调用A中的成员
private:
        int mValue;
};

补充说明

上一篇 下一篇

猜你喜欢

热点阅读