c++之派生类访问基类的友元函数

时间:2022-09-07 21:38:29

学过c++的都知道派生类是不继承基类的友元函数的,但是有时候我们还是需要访问基类的友元函数的,这样看来好像是没有什么办法了。但是c++中可以使用显式类型转化来访问。下面是写的一个测试程序
程序如下:

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

class BaseClass
{
private:
    string m_name;
public:
    BaseClass(string name);
    BaseClass(){}
    virtual ~BaseClass(){}
    friend std::ostream & operator << (std::ostream & os , const BaseClass & b);
};
class DerivedClass : public BaseClass
{
private:
    int m_age;
public:
    DerivedClass(int age, string name);
    DerivedClass(){}
    virtual ~DerivedClass(){}
    friend std::ostream & operator << (std::ostream & os , const DerivedClass & d);
};

BaseClass::BaseClass(string name) : m_name(name)
{
}

std::ostream & operator << (std::ostream & os,const  BaseClass & b)
{
    os << "m_name: " << b.m_name << endl;
    return os;
}

DerivedClass::DerivedClass(int age, string name):
    BaseClass(name)
{
    m_age = age;
}

std::ostream & operator << (std::ostream & os , const DerivedClass & d)
{
    os << (const BaseClass & ) d;//在这里进行了显式的类型转化
    os << "m_age: " << d.m_age << endl;
}

int main()
{
    DerivedClass  d(22,"郭小郭");
    cout << d << endl;
    return 0;
}