close

friend class is a class that can access the private members of a class as though it were a member of that class.

we can define an entire class as a friend as follow :

class X 
{
  int a, b;
 friend class F;
public:
  X() : a(1), b(2) { }
};

class F 
{
public:
 void print(X& x) 
 {
 cout << "a is " << x.a << endl;
    cout << "b is " << x.b << endl;
  }
};

int main() 
{
  X xobj;
  F fobj;
  fobj.print(xobj);
  return 0;
}

We can just define a function of class as friend :
#include <iostream>
using namespace std;

class X;

class Y 
{
public:
  void print(X& x);
};

class X 
{
  int a, b;
 friend void Y::print(X& x);
public:
  X() : a(1), b(2) { }
};

void Y::print(X& x)
 {
 cout << "a is " << x.a << endl;
  cout << "b is " << x.b << endl;
}

int main()
 {
  X xobj;
  Y yobj;
  yobj.print(xobj);
  return 0;
}

ref : http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr042.htm

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JerryCheng 的頭像
    JerryCheng

    KwCheng's blog

    JerryCheng 發表在 痞客邦 留言(0) 人氣()