友元函数的4种形式。。。

友元函数无非就是让一个类外的函数用这个累的私有变量。

友元函数有4种形式:

第一种:

#include <iostream.h>
class A
{
   int x;
   friend void fun();
};
void fun()
{
   A a;a.x=100;
}
void main()
{
   fun();
}

 

第二种:

 

#include <iostream.h>
class B
{
public:
 void fun();

};

 

class A
{
   int x;
   friend void B::fun();
};


void B::fun()
{
   A a;a.x=100;
}

 

void main()
{
  B q1; q1.fun();
}

 

第三种:

 

#include <iostream.h>
class A;
class B
{
public:
 void fun(A s);

};

 

class A
{
   int x;
   friend void B::fun(A s);
};


void B::fun(A s)
{
    s.x=100;
 cout<<s.x<<endl;
}

 

void main()
{
   B s1;
   A a1;
   s1.fun(a1);
 
}

 

第四种:

 

#include <iostream.h>
class A;
class B
{
public:
 void fun(A s);
 void fun1();

};

 

class A
{
   int x;
   friend class B;
};


void B::fun(A s)
{
    s.x=100;
 cout<<s.x<<endl;
}
void B::fun1()
{
 A a1;   a1.x=1000;
   cout<<a1.x<<endl;
}


void main()
{
   B s1;
   A a1;
   s1.fun(a1);
   s1.fun1();
 
}

 

大概就是这几种形式了,呵呵。

posted @ 2010-12-08 12:56  java简单例子  阅读(341)  评论(0)    收藏  举报