2011-06-18 96 views

回答

2

私有繼承
基類的所有成員Public成爲派生類&
Private成員的基類的所有成員Protected成爲派生類的Private成員。

的代碼示例:

Class Base 
{ 
    public: 
     int a; 
    protected: 
     int b; 
    private: 
     int c; 
}; 

class Derived:private Base //Not mentioning private is OK because for classes it defaults to private 
{ 
    void doSomething() 
    { 
     a = 10; //Allowed 
     b = 20; //Allowed 
     c = 30; //Not Allowed, Compiler Error 
    } 
}; 

class Derived2:public Derived 
{ 
    void doSomethingMore() 
    { 
     a = 10; //Not Allowed, Compiler Error, a is private member of Derived now 
     b = 20; //Not Allowed, Compiler Error, b is private member of Derived now 
     c = 30; //Not Allowed, Compiler Error 
    } 
}; 

int main() 
{ 
    Derived obj; 
    obj.a = 10; //Not Allowed, Compiler Error 
    obj.b = 20; //Not Allowed, Compiler Error 
    obj.c = 30; //Not Allowed, Compiler Error 

} 

如果你傾向於瞭解繼承&訪問說明,你可以在更this答案我張貼相當長的一段前退房。

0

私有繼承通常用作組合形式。與具有繼承類型的成員變量沒有多大區別。

這意味着

在某些罕見的情況下,邊緣「在...的術語實施」時,它可以比具有一個成員變量更有效。

我知道私人遺產最常見的用法是boost::noncopyable