Implementation of C++ friend class
- 2020-06-12 10:07:42
- OfStack
The friends in C++ can implement both friend functions and friend classes, meaning that a class can be a friend of another class. When a member of a class is a friend of another class, all its member functions are friends of another class and can access the private or public members of another class.
For example:
#include <iostream>
#include <cstring>
using namespace std ;
// Declaration of teacher class
class Techer ;
// Students in class
class Student
{
private:
string name ;
int age ;
char sex ;
int score ;
public :
Student(string name , int age , char sex , int score);
void stu_print(Techer &tech);
};
// The teacher class
class Techer
{
private:
string name ;
int age ;
char sex ;
int score ;
public :
Techer(string name , int age , char sex , int score);
// The statement 1 A metaclass
friend Student ;
};
//Student Class constructor implementation
Student::Student(string name , int age , char sex , int score)
{
this->name = name ;
this->age = age ;
this->sex = sex ;
this->score = score ;
}
//Techer Class constructor implementation
Techer::Techer(string name , int age , char sex , int score)
{
this->name = name ;
this->age = age ;
this->sex = sex ;
this->score = score ;
}
// print Student The private member and of the class Techer Private member of
void Student::stu_print(Techer &tech)
{
// with this A pointer accesses a member of this class
cout << this->name << endl ;
cout << this->age << endl ;
cout << this->sex << endl ;
cout << this->score << endl ;
// access Techer The members of the class
cout << tech.name << endl ;
cout << tech.age << endl ;
cout << tech.sex << endl ;
cout << tech.score << endl ;
}
int main(void)
{
Student stu1("YYX",24,'N',86);
Techer t1("hou",40,'N',99);
stu1.stu_print(t1);
return 0 ;
}
Operation results:
[
YYX
24
N
86
hou
40
N
99
conclusion