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;
}

在这里插入图片描述

发布了52 篇原创文章 · 获赞 26 · 访问量 3415

猜你喜欢

转载自blog.csdn.net/weixin_43796685/article/details/103484541