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;
}
因篇幅问题不能全部显示,请点此查看更多更全内容