C++之派生类的友元

先举个例子:

#include <iostream>

using namespace std;

class Student{
private:
    int _a;
    int _b;
public:
    Student(int a, int b):_a(a), _b(b){}
    friend ostream& operator <<(ostream& os, Student& s){
        os << s._a << "--" << s._b;
        return os;
    }
};

class Graduate: public Student{
private:
    int _c;
public:
    Graduate(int a, int b, int c):Student(a, b), _c(c){}
};

int main()
{
    Student s(1, 2);
    cout << s << endl;
    Graduate gra(3, 4, 5);
    cout << gra << endl;
    return 0;
}

输出结果为:
这里写图片描述

父类Student有一个输出流重载,可以看到子类Graduate可以利用隐式转换成父类Student,并调用了父类的友元函数,最终的输出格式跟父类一样。那如果子类想输出从父类继承的东西还有自己的东西,就得重载operator<<这个全局函数:

#include <iostream>

using namespace std;

class Student{
private:
    int _a;
    int _b;
public:
    Student(int a, int b):_a(a), _b(b){}
    friend ostream& operator <<(ostream& os, Student& s){
        os << s._a << "--" << s._b;
        return os;
    }
};

class Graduate: public Student{
private:
    int _c;
public:
    Graduate(int a, int b, int c):Student(a, b), _c(c){}
    friend ostream& operator<<(ostream& os, Graduate& gra){
        cout << static_cast<Student&>(gra);
        os << "--" << gra._c;
        return os;
    }
};

int main()
{
    Student s(1, 2);
    cout << s << endl;
    Graduate gra(3, 4, 5);
    cout << gra << endl;
    return 0;
}

输出结果为:
这里写图片描述

这里只需要注意重载的函数里内,需要先将子类显示的转换成父类的引用(以为转换过程中会形成中间变量,而这个中间变量是个临时值,所以必须用引用来接收,或者将父类友元的参数类型改成:const Student& ),去调用父类的友元,因为子类不能直接访问父类的私有成员,最后再输出自己的东西就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值