(1)设置Teacher为Student的友类,通过Teacher修改Student中的一些属性值
(2)友元是单向设置的,Teacher是Student的友类,但是Student不是Teacher的友类,如有需要则应该在Student中设置才行。
(3)友元不具有传递性,例如类A是类B的友元,类B时类C的友元,类C与类A之间如果没有说明那么就不是友元
#include<iostream>
#include<string>
class Student;
class Teacher {
public:
Teacher(int new_id,string new_name);
void SetScore(Student&S,int new_score);
private:
int id;
string name;
};
class Student {
public:
Student(int new_id, string new_name, int new_score);
int GetScore();
friend class Teacher;
private:
int id;
string name;
int score;
};
Teacher::Teacher(int new_id, string new_name) :id(new_id), name(new_name)
{
cout << "教师对象创建完成!" << endl;
}
void Teacher::SetScore(Student&S,int new_score)
{
S.score = new_score;
cout << "成绩修改成功!" << endl;
}
Student::Student(int new_id, string new_name, int new_score):id(new_id),name(new_name),score(new_score)
{
cout << "学生创建成功!" << endl;
}
int Student::GetScore()
{
cout << name << "成绩:" << score << endl;
return score;
}
int main()
{
Student S[2] = { Student(1,"mark",0),Student(2,"tom",0) };
Teacher T(1, "wang");
S[0].GetScore();
S[1].GetScore();
T.SetScore(S[0], 100);
S[0].GetScore();
system("pause");
}