静的メンバーとC ++の継承(C)---後継友人

C ++の継承

継承と友人

友情は継承されません

その基底クラスとサブクラスの友人はのアクセスprivateまたは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
おすすめ