C++继承(三)---继承中的友元与静态成员

C++继承

继承与友元
友元关系不能被继承

也就是说基类的友元并不能访问子类的私有或者protected成员
同理,可知,子类中的友元,也不能访问基类中的protected成员

class Derived; //需要进行子类声明

class Base
{
public:
	friend void print(Base &b, Derived &d);

	//private 成员在什么情况下类外都都不可访问
protected:
	int _b = 10;
};

class Derived : public Base
{
public:
	friend void print1(Base &b, Derived &d);
protected:
	int _d = 20;
};	

void print(Base &b, Derived &d)
{
	cout << "Base:" << b._b << endl;
	cout << "Derived:" << d._d << endl;//error 因为友元并不会继承
}
void print1(Base &b, Derived &d)
{
	cout << "Base:" << b._b << endl; // error 因为友元并不会继承,所以,
									 // 子类中的友元也不能访问基类中的保护成员
	cout << "Derived:" << d._d << endl;
}

int main()
{
	Base b;
	Derived d;
	print(b, d);
	print1(b, d);
	return 0;
}

这是很正常的,父亲的朋友一半情况下不是儿子的朋友,儿子的朋友一般情况下也不是父亲的朋友

继承与静态成员
基类中的静态成员可以被继承

基类中的静态成员可以被继承下去,由于是静态成员,所以,在整个继承体系中,该静态成员只有一份,无论派生出多少子类

class Base
{
public:
	void PrintBaes()
	{
		cout << static_b << endl;
		cout << static_d << endl;//error基类无法调用派生类中的静态成员函数
	}
protected:
	int _b = 10;
	static int static_b;
};
int Base::static_b = 11;//静态成员初始化

class Derived : public Base
{
public:
	void Print()
	{
		cout << static_b << endl;//派生类中访问基类的静态成员
		cout << _d << endl;
	}
protected:
	int _d = 20;
	static int static_d;
};
int Derived::static_d = 12;

int main()
{
	Derived d;
	d.Print();
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值