#include<iostream>
#include<string>
using namespace std;
class Student;
class Class
{
private:
int id;
string student_name;
public:
//因为现在还没有具体声明Student类,所以我们要把函数的实现放在Student类的声明后面
void show(const Student& s); //因为Class是Student的友元类,所以可以直接访问Student的私有数据
void student_show(const Student&); //即使Class不是Student类的友元类,这个函数也可以访问Student类的私有数据,因为它是Student类的友元成员函数
};
class Student
{
private:
string name;
int age;
int grade;
int clas;
public:
friend class Class; //友元类的声明可以放在类中任何地方
Student(string name_, int age_, int grade_, int clas_):name(name_), age(age_), grade(grade_), clas(clas_){}
friend ostream& operator<<(ostream& os, const Student& s) //友元函数
{
os << s.name << " " << s.age << " " << s.grade << " " << s.clas << endl;
return os;
}
friend void Class::student_show(const Student&); //友元成员函数
};
void Class::show(const Student& s) //因为Class是Student的友元类,所以可以直接访问Student的私有数据
{
cout << s.name << " " << s.clas << endl;
}
void Class::student_show(const Student& s)
{
cout << s.name << " " << s.age << " " << s.grade << " " << s.clas << endl;
}
int main()
{
//友元函数
Student s1("linukey", 20, 100, 1);
cout << s1;
//友元类
Class c1;
c1.show(s1);
//友元成员函数
c1.student_show(s1);
cin.get();
return 0;
}
#include<string>
using namespace std;
class Student;
class Class
{
private:
int id;
string student_name;
public:
//因为现在还没有具体声明Student类,所以我们要把函数的实现放在Student类的声明后面
void show(const Student& s); //因为Class是Student的友元类,所以可以直接访问Student的私有数据
void student_show(const Student&); //即使Class不是Student类的友元类,这个函数也可以访问Student类的私有数据,因为它是Student类的友元成员函数
};
class Student
{
private:
string name;
int age;
int grade;
int clas;
public:
friend class Class; //友元类的声明可以放在类中任何地方
Student(string name_, int age_, int grade_, int clas_):name(name_), age(age_), grade(grade_), clas(clas_){}
friend ostream& operator<<(ostream& os, const Student& s) //友元函数
{
os << s.name << " " << s.age << " " << s.grade << " " << s.clas << endl;
return os;
}
friend void Class::student_show(const Student&); //友元成员函数
};
void Class::show(const Student& s) //因为Class是Student的友元类,所以可以直接访问Student的私有数据
{
cout << s.name << " " << s.clas << endl;
}
void Class::student_show(const Student& s)
{
cout << s.name << " " << s.age << " " << s.grade << " " << s.clas << endl;
}
int main()
{
//友元函数
Student s1("linukey", 20, 100, 1);
cout << s1;
//友元类
Class c1;
c1.show(s1);
//友元成员函数
c1.student_show(s1);
cin.get();
return 0;
}