What is difference between protected and private derivation in c++
Possible Duplicate:
Difference between private, public and protected inheritance in C++
C++中保护或私有派生的区别是什么?我想不出来,因为这两种方法似乎都限制了从派生类对象对基类成员的访问。
让我们考虑一个代码示例,说明使用不同的继承级别将允许(或不允许)什么:
1 2 3 4 5 6 7 8 9 10 11 | class BaseClass {}; void freeStandingFunction(BaseClass* b); class DerivedProtected : protected BaseClass { DerivedProtected() { freeStandingFunction(this); // Allowed } }; |
1 2 3 4 5 | void freeStandingFunctionUsingDerivedProtected() { DerivedProtected nonFriendOfProtected; freeStandingFunction(&nonFriendOfProtected); // NOT Allowed! } |
非友元(类、函数等)不能将
1 2 3 4 5 6 7 | class DerivedFromDerivedProtected : public DerivedProtected { DerivedFromDerivedProtected() { freeStandingFunction(this); // Allowed } }; |
从
1 2 3 4 5 6 7 | class DerivedPrivate : private BaseClass { DerivedPrivate() { freeStandingFunction(this); // Allowed } }; |
1 2 3 4 5 6 7 | class DerivedFromDerivedPrivate : public DerivedPrivate { DerivedFromDerivedPrivate() { freeStandingFunction(this); // NOT allowed! } }; |
最后,一个继承层次较低的非友元类看不到
使用此矩阵(从此处获取)确定继承成员的可见性:
1 2 3 4 5 6 | inheritance\member | private | protected | public --------------------+-----------------+---------------+-------------- private | inaccessible | private | private protected | inaccessible | protected | protected public | inaccessible | protected | public --------------------+-----------------+---------------+-------------- |
例1:
1 2 | class A { protected: int a; } class B : private A {}; // 'a' is private inside B |
。
例2:
1 2 | class A { public: int a; } class B : protected A {}; // 'a' is protected inside B |
例3:
1 2 | class A { private: int a; } class B : public A {}; // 'a' is inaccessible outside of A |
我在这个问题中添加了一个非常详细的关于
基本上,