关于C++友元类的实现讲解
C++中的友元既可以实现友元函数,也可以实现友元类,也就是说一个类也可以作为另外一个类的友元。当作为一个类的友元时,它的所有成员函数都是另一个类的友元函数,都可以访问另一个类的私有或者公有成员。
请看实例:
#include#include usingnamespacestd; //声明教师类 classTecher; //学生类 classStudent { private: stringname; intage; charsex; intscore; public: Student(stringname,intage,charsex,intscore); voidstu_print(Techer&tech); }; //教师类 classTecher { private: stringname; intage; charsex; intscore; public: Techer(stringname,intage,charsex,intscore); //声明一个友元类 friendStudent; }; //Student类的构造函数的实现 Student::Student(stringname,intage,charsex,intscore) { this->name=name; this->age=age; this->sex=sex; this->score=score; } //Techer类的构造函数的实现 Techer::Techer(stringname,intage,charsex,intscore) { this->name=name; this->age=age; this->sex=sex; this->score=score; } //打印Student类中的私有成员和Techer的私有成员 voidStudent::stu_print(Techer&tech) { //用this指针访问本类的成员 cout< name< age< sex< score< 运行结果:
YYX
24
N
86
hou
40
N
99总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。