类成员函数和类作为友元使用

 

类成员函数可以作为友元在其他类中声明。考虑下面的例子:

 

//  classes_as_friends1.cpp
//  C2248 expected
class  B;
class  A
{
    
int Func1( B& b ) ;
    
int Func2( B& b ) ;
}
;

class  B
{
private:
    
int _b;
    friend 
int A::Func1( B& );   //  Grant friend access to one,给A类中的Func1函数访问B类的权限。
                                
//   function in class B. 
}
;
 
int  A::Func1( B &  b )  return b._b; }   //   OK: this is a friend.
  int  A::Func2( B &  b )  return b._b; }   //   Error: _b is a private member.

 在之前的例子当中,只有A::Func1( B& ) 被声明为B类的友元。因此,对私有成员_b的访问在Func1中是正确的,但是在Func2中不正确。

友元类指的是该类中所有的成员函数都是友元函数,也就是说,所有的成员函数都有访问其他类(被声明的类)私有以及保护成员的权限。假设B类中有关于friend的如下声明:

 

friend  class  A;

A类中的所有成员函数被赋予了访问B类的权限(友元的权限)。下面是一个友元类的例子:

 

//  classes_as_friends2.cpp
//  compile with: /EHsc
#include  < iostream >

using   namespace  std;
class  YourClass
{
friend 
class YourOtherClass;  // Declare a friend class
public:
   YourClass() : topSecret(
0){}
   
void printMember() { cout << topSecret << endl; }
private:
   
int topSecret;
}
;

class  YourOtherClass
{
public:
   
void change( YourClass& yc, int x ){yc.topSecret = x;}
}
;

int  main()  {
   YourClass yc1;
   YourOtherClass yoc1;
   yc1.printMember();
   yoc1.change( yc1, 
5 );
   yc1.printMember();
}

这种友元的关系(friendship)是不明确的,除了明确声明的情况下(指在类中写了frined class XXX)。在上面的例子中,YourClass 有访问YourOtherClass的私有成员的权限。

友元的关系不能够被继承,这意味着YourOtherClass 的子类不能够访问YourClass 的私有成员。友元的关系也不能够传递,所以YourOtherClass 的友元不能够访问YourClass 的私有成员。

下面的图中有四个类声明: Base, Derived, aFriend, 和 anotherFriend。在其中只有aFriend 有直接访问Base的私有成员的权限(以及Base从其它类继承来的成员,图中没有表示)。

Implications of friend Relationship

ps:注意不要把声明友元类的位置搞混。类B要在成员函数中操纵类A的成员,需要在类A中写friend class B;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值