搜索
您的当前位置:首页What are the differences between protected and private inheritance?

What are the differences between protected and private inheritance?

来源:乌哈旅游

概念

the differences between protected and private inheritance primarily relate to the accessibility of base class members in derived classes and outside the class hierarchy:



例子

#include <iostream>
using namespace std;

class Base
{
private:
    int pvt = 1;

protected:
    int prot = 2;

public:
    int pub = 3;

    // function to access private member
    int getPVT() { return pvt; }
};

class ProtectedDerived : protected Base
{
public:
    // function to access protected member from Base
    int getProt() { return prot; }

    // function to access public member from Base
    int getPub() { return pub; }

    // function to get access to private members from Base
    int try_getPVT() { Base::getPVT(); }
};

int main()
{
    ProtectedDerived object1;
    cout << "Private = " << object1.try_getPVT() << endl;
    cout << "Protected = " << object1.getProt() << endl;
    cout << "Public = " << object1.getPub() << endl;
    return 0;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Top