#include<iostream.h>
#include<string.h>
class Student
{
private:
char name[20],number[20];
friend void show(Student&st) //友元函数的声明和定义
{
cout<<"姓名:"<<st.name<<endl<<"学号:"<<st.number<<endl;
}
public:
Student(char *s1,char *s2)
{
strcpy(name,s1);
strcpy(number,s2);
}
};
class Score
{
private:
unsigned int i1,math,physics,english;
friend void show_all(Student&,Score*); //友元函数的声明
public:
Score(unsigned int i1,unsigned int i2,unsigned int i3):math(i1),physics(i2),english(i3)
{ }
};
void show_all(Student&st,Score *sc) // 友元函数的定义
{
show(st);
cout<<"数学 :"<<sc->math<<endl<<"物理 :"<<sc->physics<<endl;
cout<<"英语 :"<<sc->english<<endl;
}
void main()
{
Student wen("wenxianliang","3081817124");
Score cs(85,89,94);
show_all(wen,&cs);
}
02
//下面是友元函数的定义和使用 学生姓名 成绩
#include<iostream.h>
#include<string.h>
class Student //学生类的定义
{
private:
char name[20],number[14];
public:
Student(char *s1,char *s2)
{
strcpy(name,s1);
strcpy(number,s2);
}
friend void show(Student *st) //友元函数的定义
{
cout<<"姓名:"<<st->name<<endl;
cout<<"学号:"<<st->number<<endl;
}
};
class Score //成绩类的定义
{
private:
unsigned int math,physics,english;
public:
Score(unsigned int i1,unsigned int i2,unsigned int i3)
{
math=i1;physics=i2; english=i3;
}
friend void show_all(Score sc) //友元函数的定义
{
cout<<"数学:"<<sc.math<<endl;
cout<<"物理:"<<sc.physics<<endl;
cout<<"英语:"<<sc.english<<endl;
}
};
void main()
{
Student wen("wenxianliang","3081817124");
Score score(85,95,89);
show(&wen);
show_all(score);
}