public, protected, private
Take a look at this code:
#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.public开发者_如何学Cfield << a.protectedfield << endl;
}
};
int main()
{
B b;
b.test();
b.test2();
return 0;
}
B has access to this->protectedfield but hasn't to a.protectedfield. Why? Yet B is subclass of A.
B has access only to the protected fields in itself or other objects of type B (or possibly derived from B, if it sees them as B-s).
B does not have access to the protected fields of any other unrelated objects in the same inheritance tree.
An Apple has no right to access the internals of an Orange, even if they are both Fruits.
class Fruit
{
protected: int sweetness;
};
class Apple: public Fruit
{
public: Apple() { this->sweetness = 100; }
};
class Orange: public Fruit
{
public:
void evil_function(Fruit& f)
{
f.sweetness = -100; //doesn't compile!!
}
};
int main()
{
Apple apple;
Orange orange;
orange.evil_function(apple);
}
this->protectedfield: B enherits of A, this means protectedfield is a property of itself now, so it is able to access it.
a.protectedfield: a is a member of class B, this member has the protectedfield variable which is protected. B cannot touch it, because protected means only access from A within.
Lets break the whole code in small parts.Copy and paste this two code and try to compile!!!!
#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.
}
Now B inherits class A as private
#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!!!!
}
Thanks!
精彩评论