头图

Slide2.PNG
例45-1:

#include <iostream>
#include <string>
#include <sstream>
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继承

父类中公有成员变为保护成员,其他成员保持不变
Slide6.PNG
继承与访问级别深度实践45-2:

#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, 所以所有的成员全部变成了 private 成员, 因此外界无法访问
    
    a.set(1, 1, 1);
    // b.set(2, 2, 2);
    // c.set(3, 3, 3);
    
    a.print();
    b.print();
    c.print();
    
    return 0;
}

输出:

m_a1
m_b1
m_c1
m_a134515136
m_b-1077692488
m_c11012485
m_a134515161
m_b12231460
m_c12230644

一般而言,C++工程项目中只使用public继承

C++派生语言只支持一种继承方式(public继承)

protected和private继承带来的复杂性远大于实用性

小结:

Slide10.PNG


YingLi
6 声望4 粉丝

From zero to hero.