A common function can be a friend function of multiple classes., We modify the above Code and observe the changes:
# Include <iostream>
Using namespace std;
Class Country;
Class Internet
{
Public:
Internet (char * name, char * address)
{
Strcpy (Internet: name, name );
Strcpy (Internet: address, address );
}
Friend void ShowN (Internet & obj, Country & cn); // pay attention to this
Public:
Char name [20];
Char address [20];
};
Class Country
{
Public:
Country ()
{
Strcpy (cname, "China ");
}
Friend void ShowN (Internet & obj, Country & cn); // pay attention to this
Protected:
Char cname [30];
};
Void ShowN (Internet & obj, Country & cn)
{
Cout <cn. cname <"|" <obj. name <endl;
}
Void main ()
{
Internet a ("China Software Development Lab", "www.cndev-lab.com ");
Country B;
ShowN (a, B );
Cin. get ();
}
A member function of a class can also be a friend of another class,This allows a member function of a class to operate on data members of another class. In the following code, add a Country class. observe the following:
# Include <iostream>
Using namespace std;
Class Internet;
Class Country
{
Public:
Country ()
{
Strcpy (cname, "China ");
}
Void editurl (Internet & temp); // declaration of member functions
Protected:
Char cname [30];
};
Class Internet
{
Public:
Internet (char * Name, char * address)
{
Strcpy (Internet: Name, name );
Strcpy (Internet: Address, address );
}
Friend void country: editurl (Internet & temp); // you can declare the function.
Protected:
Char name [20];
Char address [20];
};
Void Country: Editurl (Internet & temp) // external definition of the member function
{
Strcpy (temp. address, "edu.cndev-lab.com ");
Cout <temp. name <"|" <temp. address <endl;
}
Void main ()
{
Internet a ("China Software Development Lab", "www.cndev-lab.com ");
Country B;
B. Editurl ();
Cin. get ();
}
The entire class can also be a friend of another class.The friend can also be calledFriends. Each member function of a friend class can access all the members of another class.