C++深度解析 不同的继承方式 --- public继承(44)
继承
冒号(:)表示继承关系关系
class Parent
{
};
class Child : public Parent
{
};
Parent表示被继承的类,public的意义是什么?
示例程序:
#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;
}
C++中支持三种不同的继承方式
public继承
- 父类成员在子类中保持原有访问级别
private继承
- 父类成员在子类中变为私有成员
protected继承
- 父类中的公有成员变为保护成员,其他成员保持不变
C++中的默认继承方式为private。
示例程序:
#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 printf()
{
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 printf()
{
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 printf()
{
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_B 私有继承自 Parent,所以所有的public成员全部变成了private成员,因此外界无法访问
a.set(1, 1, 1);
//b.set(2, 2, 2);
//c.set(3, 3, 3);
a.printf();
b.printf();
c.printf();
return 0;
}
一般而言,C++工程项目中只使用public继承。
C++的派生语言只支持一种继承方式(public继承)。
protected和private继承带来的复杂性远大于实用性。
小结
C++中支持3种不同的继承方式
继承方式直接影响父类成员在子类中的访问属性
一般而言,工程中只使用public的继承方式
C++的派生语言中只支持public继承方式