讓我們打破小部分的整個代碼。複製並粘貼這兩個代碼,並嘗試編譯!!!!
#include <iostream>
using namespace std;
class A
{
private:
int privatefield;
protected:
int protectedfield;
public:
int publicfield;
};
int main()
{
A a;
cout<<a.publicfield;
cout<<a.privatefield;/////not possible ! private data can not be seen by an object of that class
cout<<a.protectedfield;////again not possible. protected data is like privete data except it can be inherited by another.If inherited as private then they are private,if as protected then protected and if as public then also protected.
}
現在乙繼承類A私有
#include <iostream>
using namespace std;
class A
{
private:
int privatefield;
protected:
int protectedfield;
public:
int publicfield;
};
class B: private A
{
private:
A a;
public:
void test()
{
cout << this->publicfield << this->protectedfield << endl;
}
void test2()
{
cout << a.publicfield << endl;
}
};
int main()
{
/*Now B will have both public and protected data as private!!!!
That means
B now looks like this class
Class B
{
private:
int protectedfield;
int publicfield;
}
As we have discussed private/protected data can not be accessed by object of the class
so you you can not do things like this
B b;
b.protectedfield; or b.publicfield;
*/
B b;
b.privatefield;////Error !!!
b.protectedfield/////error!!!!
}
謝謝!
不,B不是A的子類。如果你使用公有繼承,那將是。 – 2010-08-02 14:07:00
[Here](http://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance-in-c/1372858#1372858)是一個解釋它是如何工作的。 – 2010-08-02 14:28:18
爲什麼?私有繼承意味着所有繼承的字段和方法都將變爲私有,所以它們只能在派生類中訪問。 – l245c4l 2010-08-02 14:58:13