c++编程思想2 --友元存储控制

来源:互联网 发布:杭州算法工程师招聘 编辑:程序博客网 时间:2024/05/18 00:16

 友元friend在c++中的应用 

我们知道在c++的类访问权限中,private和 protected在类外面进行访问的时候 会因为权限而不能访问 ,友元就解决了这个问题 。

可以这样理解,他为外部的 函数 或者类 进行了 访问授权,其实这已经超出OOP的范畴,但是对于C++而言是以实用为主,所以说C++并不是完全面向对象的语言

C++这一特性就破坏的C++的安全性 。

我们要使用友元函数或者类 我们就要在类的定义中用 friend 进行相应的声明 。。。

 

下面是友元函数的利用 ,我们利用友元函数进行对于类的私有成员和保护成员进行修改

#include <iostream>
using namespace std ;
class  A
{
public:
 A()
 {
  this->x=0;
  this->y=0 ;
 }
 void Show()
 {
  cout<<"x="<<this->x<<endl;
  cout<<"y="<<this->y<<endl;
 }
 friend void Add(A*) ;
private:
 int x ;
protected:
 int y;
};
void Add(A* a)
{
 a->x++;
 a->y++;
}
void main()
{
    A * a=new A() ;
 Add(a) ;
 a->Show() ;
}

 下面是利用对于内部类进行授权进行访问,对于内部类来说我们 在类内部声明,但是并没有赋予内部类访问包容类私有成员的权限所以我们要利用friend将内部类声明

为全局. 注意在java中 内部类是具有访问外部类的权限的 。

#include <iostream>
using namespace std ;
class A
{
private:
  int x ;
public :
 A()
 {
  this->x=0 ;
 }
 class B
 {
 public:
  void add(A *tem)
  {
   tem->x++;
  }
 };
 friend A::B ;    //对内部类进行全局声明
 void show()
 {
     cout<<"x="<<this->x<<endl ;
 }
 
};
void main()
{
 A::B c ;   
 A a ;
 c.add(&a);
    a.show();
}

3、利用友元类进行访问

#include <iostream>
using namespace std ;
class A
{
public:
 A()
 {
  x=0 ;
 }
 void show()
 {
  cout<<"x="<<x<<endl ;
 }
 friend  class  B ;
private:
 int x ;
};
class  B
{
public:
 A a ;
 void add()
 {
  a.x++ ;
 }
};
void main()
{
 B  b;
 b.add() ;
 b.a.show() ;
}