不同的继承方式

继承父类为啥要修饰符public

  • 继承中的public 、protected、private

三种继承方式

  • public继承

    • 父类成员在子类中保持原有访问级别
  • private继承

    • 父类成员在子类中变为私有成员
  • protected继承

    • 父类中公有成员变成保护程艳,其他成员保持不变

    = MAX{继承方式,父类成员访问属性}
    C++ 默认为private

#include <iostream>
#include <string>

using namespace std;

class Parent
{
};

class Child_A : public Parent
{
};

class Child_B : protected Parent
{
};

class Child_C : private Parent
{
};

int main()
{   
    return 0;
}

不同的继承方式

#include <iostream>
#include <string>

using namespace std;

class Parent
{
protected:
	int m_a;
protected:
	int m_b;
public:
	int m_c;
	void set(int a, int b, int c)
	{
		m_a = a;
		m_b = b;
		m_c = c;
	}
};


class Child_A : public Parent
{
public:
	void print()
	{
		cout << "m_a" << m_a << endl;
		cout << "m_b" << m_b << endl;
		cout << "m_c" << m_c << endl;
	}
	
};

class Child_B : protected Parent
{
public:
	void print()
	{
		cout << "m_a" << m_a << endl;
		cout << "m_b" << m_b << endl;
		cout << "m_c" << m_c << endl;
	}
};

class Child_C : private Parent
{
public:
	void print()
	{
		cout << "m_a" << m_a << endl;
		cout << "m_b" << m_b << endl;
		cout << "m_c" << m_c << endl;
	}
};

int main()
{   
	Child_A a;
	Child_B b;
	Child_C c;
	a.m_c = 100;
	//b.m_c = 100; //Child_B 保护继承来源Parent,父类所有public成员变成protected成员,因此外界无法访问
	//c.m_c = 100; //Child_C 保护继承来源Parent,父类所有public成员变成private成员,因此外界无法访问
	
	a.set(1,1,1);
	//b.set(1,1,1);
	//c.set(1,1,1);
	
	
	a.print();
	b.print();
	c.print();
	
	
    return 0;
}

protected和private继承复杂性大于实用性

一般用public

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值