C++ 实验三 友元函数

本文详细介绍了C++中友元函数的四种实现方式,包括非成员函数、成员函数、友元类和类的组合。通过具体的代码示例,展示了如何在Student和Score类中应用这些友元机制,以及遇到的问题和解决方案,如Show2无法访问私有成员的报错。同时,提供了所有实验源码的GitHub链接。

前言

🎬本文章是 【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 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值