继承关系的特殊性-派生类继承了友元函数

p182

程序说明:基类Base的成员函数print()是另一个类another的友元函数,所以再print()中可以访问another的私有成员变量aaa。类Derived是类Base的派生类,他从类Base继承了print()函数。也就是说,通过Derived对象也能调用print()函数访问another的私有成员aaa。 //在主函数中,通过类Base的变量a调用print()函数,调用的是基类中定义的版本。输出结果是Base:10。

#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;//将aaa初始化为100
	a.print(ano);//输出:Base:100
	d.print(ano);//输出:Base:100
	return 0;
	//程序说明:基类Base的成员函数print()是另一个类another的友元函数,所以再print()中可以访问another的私有成员变量aaa。类Dericved是类Base的派生类,他从类Base继承了print()函数。也就是说,通过Derived对象也能调用print()函数访问another的私有成员aaa。
	//在主函数中,通过类Base的变量a调用print()函数,调用的是基类中定义的版本。输出结果是Base:10。
}

继承关系的特殊性-派生类继承了友元函数

通过派生类Derived的对象d调用print()函数因为没有重写所以执行的是继承自基类Base的版本,输出的内容依旧是Base:100 。

如果派生类Derived中重写了print()函数,若还想在函数中访问another的成私有成员,则必须将类Derived的print()函数也声明为another的友元。在类another中需要添加如下的声明。

friend void Derived::print(const another &K);//派生类的成员函数声明为本类的友元

类Derived中的print()函数定义如下:

void Derived::print(const another &K)

{

cout << "Drived: << K.aaa << endl;

}

此时再通过派生类Derived的对象d调用print()函数,执行的也将是派生类中的版本,

此时输出内容是Derived:100。通过基类对象a调用print()函数时输出维持原样。

如果基类中的成员是静态的,则在其派生类中,被继承的成员也是静态的,即其静态属性随静态成员被继承。

如果基类的静态成员是共有或者保护的,则它们被其派生类继承为派生类的静态成员。

访问这些成员时,通常用“<类名>::<成员名>”的方式去调用,无论有多少个对象被创建,这些成员都只有一个拷贝,他为基类和派生类的所有对象所共享。

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
C++

派生类改变基类中成员的访问权限

2023-10-22 17:59:09

C++

C++继承派生_文字概述

2023-10-22 18:52:13

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索