C ++ youyuan (2)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.