[C++]友元函数、友元类 friend

友元函数

When the function is declared as a friend, then it can access the private and protected data members of the class.

#include <iostream>
#include <string>
using namespace std;
class sample{
   int length, breadth;
  
   public:
   sample(int length, int breadth):length(length),breadth(breadth)
   {}
   friend void calcArea(sample s); //friend function declaration
  
};
//friend function definition
void calcArea(sample s){
   cout<<"Area = "<<s.length * s.breadth;
   }
int main()
   {
      sample s(10,15);
      calcArea(s);
  
      return 0;
}

友元类

class A{
……
friend class B;
};
class B{
……..
};

As depicted above, class B is a friend of class A. So class B can access the private and protected members of class A.

But this does not mean that class A can access private and protected members of the class B. Note that the friendship is not mutual unless we make it so.

Similarly, the friendship of the class is not inherited. This means that as class B is a friend of class A, it will not be a friend of the subclasses of class A.

#include <iostream>
#include <string>
using namespace std;
class Area{
   int length,breadth,area;
  
   public:
  
   Area(int length,int breadth):length(length),breadth(breadth)
   {}
   void calcArea(){
      area = length * breadth;
   }
  
   friend class printClass;
  
};
class printClass{
  
   public:
   void printArea(Area a){
      cout<<"Area = "<<a.area;
   }
 };
int main(){
   Area a(10,15);
   a.calcArea();
   printClass p;
   p.printArea(a);
  
   return 0;
}

源自:https://www.softwaretestinghelp.com/friend-functions-in-cpp/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值