45、不同的继承方式

public继承:父类成员在子类中保持原有的访问级别。

private继承:父类成员在子类中变为私有成员。

protected继承:父类中的公有成员变为保护成员,其他成员保持不变。

继承成员的访问属性=max{ 继承方式,父类成员的访问属性 }

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 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;

}

一般而言,c++工程项目中只使用 public 继承。c++的派生语言只支持一种继承方式(public继承),protected 和 private 继承带来的复杂性远大于实用性。

猜你喜欢

转载自blog.csdn.net/ws857707645/article/details/80251254
今日推荐