這次主要搞清了類的成員和繼承方式中的protected屬性。簡單說,它對內可見,對外私有。與private屬性不同的是,對於父類中的protected成員,繼承後在子類中依然可見。如果上述繼承以private方式進行,protected成員在繼承後會成爲private成員。
//demo of the inherency property in C++
#include <iostream.h>
class Base
{
private:
char *pv;
protected:
char *pt;
public:
char *pb;
Base()
{
this->pv = "private";
this->pt = "protected";
this->pb = "public";
}
};
class Pv_Base:private Base
{
public:
void show()
{
//cout<<this->pv<<" in Pv_Base.show()"<<endl; //error
cout<<this->pt<<" in Pv_Base.show()"<<endl;
cout<<this->pb<<" in Pv_Base.show()"<<endl;
}
};
class Pt_Base:protected Base
{
public:
void show()
{
//cout<<this->pv<<" in Pt_Base.show()"<<endl; //error
cout<<this->pt<<" in Pt_Base.show()"<<endl;
cout<<this->pb<<" in Pt_Base.show()"<<endl;
}
};
class Pb_Base:public Base
{
public:
void show()
{
//cout<<this->pv<<" in Pb_Base.show()"<<endl; //error
cout<<this->pt<<" in Pb_Base.show()"<<endl;
cout<<this->pb<<" in Pb_Base.show()"<<endl;
}
};
void main()
{
Base base;
//cout<<base.pv<<" in main()"<<endl; //error
//cout<<base.pt<<" in main()"<<endl; //error
cout<<base.pb<<" in main()"<<endl;
cout<<endl;
Pv_Base pv_base;
//cout<<pv_base.pv<<" in main()"<<endl; //error
//cout<<pv_base.pt<<" in main()"<<endl; //error
//cout<<pv_base.pb<<" in main()"<<endl; //error
pv_base.show();
cout<<endl;
Pt_Base pt_base;
//cout<<pt_base.pv<<" in main()"<<endl; //error
//cout<<pt_base.pt<<" in main()"<<endl; //error
//cout<<pt_base.pb<<" in main()"<<endl; //error
pt_base.show();
cout<<endl;
Pb_Base pb_base;
//cout<<pb_base.pv<<" in main()"<<endl; //error
//cout<<pb_base.pt<<" in main()"<<endl; //error
cout<<pb_base.pb<<" in main()"<<endl;
pb_base.show();
cout<<endl;
}