【C++学习笔记9】实验9-类与对象知识进阶(3)

编写程序:
有一个学生类(Student)包含:
私有成员数据:
string name;
double score;
公有成员函数:
构造函数
友元函数
有一个教师类(Teacher)包含:
私有成员数据:
string name;
string pro;
公有成员函数:
构造函数
友元函数
提示:这两个类公用一个友元函数
输入:

输出:
student’s name:jack
99
teacher’s name:mac
professor

#include<iostream>
#include<string>
using namespace std;
class Teacher;



class Student{
    private:
        string name;
        double score;
    public:
        Student(string n,double s){
            name=n;
            score=s;
        }
        friend void print(const Student &s,const Teacher &t);//友元函数

};
class Teacher{
    private:
        string name;
        string pro;
    public:
        Teacher(string n,string p){
            name=n;
            pro=p;
        }
        friend void print(const Student &s,const Teacher &t);//友元函数
};




void print(const Student &s,const Teacher &t){
	cout<<"student's name:"<<s.name<<" "<<s.score<<endl;
	cout<<"teacher's name:"<<t.name<<" "<<t.pro<<endl;
}
int main(){
	Student student("jack",99);
	Teacher teacher("mac","professor");
	print(student,teacher);
	return 0;	
}

编写程序:
编写课程类(Course)包含:
私有成员数据:
string name;
double score;
公有成员函数:
构造函数
友元类
输入:

输出:
student’s
name:jack,course’s
name:math 89

#include<iostream>
#include<string>
using namespace std;
class Course;
class Student{
private:
	string name;
	int age;
public:
	Student(string name,double score){
		this->name = name;
		this->age = score;
	}
	void print(const Course &c);
	void print(const Course &c) const;
};





class Course{
    private:
        string name;
        double score;
    public:
        Course(string n,double s){
            name=n;
            score=s;
        }
        friend Student;//友元类
};





void Student ::print(const Course &c){
	cout<<"student's name:"<<name<<",course's name:"<<c.name<<" "<<c.score<<endl;
}
int main(){
	Student student("jack",22);
	Course course("math",89);
	student.print(course);
	return 0;	
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值