派生类继承了友元函数(P181)

/*

*继承关系的特殊性

a.如果基类有友元类或友元函数,则其派生类不会因继承关系而也有此友元类或友元函数。
b.如果基类是某类的友元,则这种友元关系是被继承的。

*/

#include<iostream>
using namespace std;

class another;
class Base
{
private:
float x;
public:
void print(const another &K);
};
class Derived:public Base
{
private:
float y;
};

class another
{
private:
int aaa;
public:
another()
{
aaa=100;
}
friend void Base::print(const another &K); //基类的成员函数声明为本类的友元
};

void Base::print(const another &K)
{
cout<<"Base:"<<K.aaa<<endl; //可以访问私有成员变量
}

int main()
{
Base a;
Derived d;
another ano;
a.print(ano);
d.print(ano);
return 0;
}

posted @ 2020-03-19 19:53  CollisionDimension  阅读(547)  评论(0)    收藏  举报