前言
🎬本文章是 【C++笔记】 专栏的文章,主要是C++黑马的笔记、自己的实验与课设
🔗C++笔记 传送门
一、要求
【项目】定义Student类和Score类,输出一个学生的成绩单(包括学号、姓名、高数、英语、政治、C++成绩)
【要求:】使用友元的不同形式加以实现
形式1:非成员函数作为友元函数
形式2:成员函数作为友元函数
形式3:友元类
形式4:类的组合
二、分析
设计Student和Score类
1.分别在Student和Score类中声明friend void show(Student student,Score score);,通过调用show函数实现非成员函数作为友元函数,之后通过main函数调用
2.设计Show2类,分别在Student和Score类中声明friend void Show2::visitinfo(Student student, Score score);,在Show2类中编写输出函数visitinfo,之后在main函数中调用
3.设计Show3类,分别在Student和Score类中声明friend class Show3;,在Show3中编写void visit(Student student,Score score)函数,之后通过Show3新建对象,调用该函数
4.设计Show4类,利用组合类在成员函数中定义Student stu与Score sc,之后通过Show4的构造函数调用Student类和Score类中的print函数
三、代码
💻提示:所有实验源码已在github整理
#include<iostream>
using namespace std;
#include<string>
class Student;
class Score;
//2.成员函数作为友元函数
class Show2
{
public:
void visitinfo(Student student,Score score);
};
class Student
{
friend void show(Student student,Score score);
friend void Show2::visitinfo(Student student, Score score);
friend class Show3;
public:
Student(string stu_id, string stu_name)
{
this->stu_id = stu_id;
this->stu_name = stu_name;
}
private:
string stu_id;
string stu_name;
};
class Score
{
friend void show(Student student,Score score);
friend void