C++友元复习

#include<iostream>
#include<string>


using namespace std;


class Student;


class Class
{
private:
int id;
string student_name;
public:
//因为现在还没有具体声明Student类,所以我们要把函数的实现放在Student类的声明后面
void show(const Student& s); //因为Class是Student的友元类,所以可以直接访问Student的私有数据
void student_show(const Student&);  //即使Class不是Student类的友元类,这个函数也可以访问Student类的私有数据,因为它是Student类的友元成员函数
};


class Student
{
private:
string name;
int age;
int grade;
int clas;
public:
friend class Class; //友元类的声明可以放在类中任何地方
Student(string name_, int age_, int grade_, int clas_):name(name_), age(age_), grade(grade_), clas(clas_){}
friend ostream& operator<<(ostream& os, const Student& s) //友元函数
{
os << s.name << " " << s.age << " " << s.grade << " " << s.clas << endl;
return os;
}
friend void Class::student_show(const Student&); //友元成员函数
};


void Class::show(const Student& s) //因为Class是Student的友元类,所以可以直接访问Student的私有数据
{
cout << s.name << " " << s.clas << endl;
}
void Class::student_show(const Student& s)
{
cout << s.name << " " << s.age << " " << s.grade << " " << s.clas << endl;
}


int main()
{
//友元函数
Student s1("linukey", 20, 100, 1);
cout << s1;


//友元类
Class c1;
c1.show(s1);


//友元成员函数
c1.student_show(s1);


cin.get();
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值