C++三种继承方式--------保护继承(protected)

保护继承表现出来的特征在共有继承、私有继承dou'都能找到有交叉的地方。通常保护继承的子类访问父类成员的权限和公有继承的子类访问父类成员的quan权限相同,保护继承的子类对象访问父类成员的权限和私有继承子类对象访问父类成员的权限相同。具体来说,保护继承的特点是父类的所有公有成员和保护成员都成为子类的保护成员都成为子类的保护成员,并且只能被他的子类成员函数或友元访问,父类的私有成员仍然是私有的,子类的成员不可以直接访问父类成员。

使用保护继承方式的父类公有或保护成员可以传递给孙子类,在孙子中可以被正常访问,这一点和私有继承不同,在保护继承中,父类的公有成员到子类中,其属性将降级为保护成员。

请看代码5.cpp

#include <iostream>
using namespace std;

class A
{
private:
    int a;
protected:
    int b;
public:
    int c;
	void show()
	{
		cout << "a = " << a << "b = " << b << "c = " << c <<endl;
	}
	
	void set_a(int a)
	{
		this->a = a;
	}
};

class B:protected A
{
public:
    void set_a(int a)
	{
		A::set_a(a);
	}
	
	void set_b(int b)
	{
		this->b = b;
	}
};

class C:protected B
{
	
};

int main()
{
    C c;
	c.set_a(10);
	c.set_b(20);
	c.c = 30;
	c.show();
    return 0;
}

编译时会出现以下错误信息

             :

由错误信息可以得知错误原因是保护继承中的公有成员的属性被降级成protected,比如类A中的公有成员c,到类B中成员c的属性将变成protected,类B中的公有成员get_a(),get_b()在类C中的属性也变成protected,所以类C的对象不能访问这些protected成员,要使上面的chen程序输出预料的结果可在类C中设计两个公有成员,程序6.cpp如下:

#include <iostream>
using namespace std;

class A
{
private:
    int a;
protected:
    int b;
public:
    int c;
	void show()
	{
		cout << "a = " << a << "b = " << b << "c = " << c <<endl;
	}
	
	void set_a(int a)
	{
		this->a = a;
	}
};

class B:protected A
{
public:
    void set_a(int a)
	{
		A::set_a(a);
	}
	
	void set_b(int b)
	{
		this->b = b;
	}
};

class C:protected B
{
public:
    void set(int a,int b,int c)
	{
		set_a(a);
		set_b(b);
		this->c = c;
	}
	
	void show()
	{
		A::show();
	}
};

int main()
{
    C c;
    c.set(10,20,30);
	c.show();
    return 0;
}

运行结果如下:

a=10 b=20 c=30

猜你喜欢

转载自blog.csdn.net/yue_jijun/article/details/81071469