C ++ inheritance (c) --- succession friend with static members

C ++ inheritance

Inheritance and friend

Friendship is not inherited

That friend of the base class and subclass can not access private or protected members of the
same reason, it is found in the subclass friend, you can not access the protected members of the base class

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

This is normal, his father's friend half the cases not the son of a friend, the son of a friend under normal circumstances is not the father of a friend

Inheritance and static member

Base class static members can be inherited

Base class static members can be inherited it, because it is a static member, therefore, the entire inheritance system, the only one static member , no matter how many derive subclasses

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

Here Insert Picture Description

Published 52 original articles · won praise 26 · views 3415

Guess you like

Origin blog.csdn.net/weixin_43796685/article/details/103484541