继承父类为啥要修饰符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;
}