让我们把整个代码分成小部分。复制并粘贴这两个代码并尝试编译!!!!
#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.
}
现在 B 继承类 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!!!!
}
谢谢!