编写程序:
有一个学生类(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;
}