C++中设置友类以及友类的特性

(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");
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值