例15.5 访问基类成员。
class stud //声明基类
{private,//基类私有成员
int num;
char name[10];
char sex;
public,//基类公用成员
void display( )
{cout<<"num,"<<num<<endl;
cout<<"name,"<<name<<endl;
cout<<"sex,"<<sex<<endl; }
}; class student,public stud //声明一个公用派生类
{
private:
int age;
char addr[30];
public:
void show( )
{ cout<<"num,"<<num<<endl; //企图引用基类的私有成员,错误。
cout<<"name,"<<name<<endl; //企图引用基类的私有成员,错误。
cout<<"sex,"<<sex<<endl; //企图引用基类的私有成员,错误。
cout<<"age,"<<age<<endl; //引用派生类的私有成员,正确。
cout<<"address,"<<addr<<endl;} //引用派生类的私有成员,正确。
};
由于基类的私有成员对派生类来说是不可访问的,因此在派生类中的show函数中直接引用基类的私有数据成员num,name和sex是不允许的。可以通过基类的公用成员函数来引用基类的私有数据成员。上面对派生类student的声明可改为
class student,public stud //声明一个公用派生类
{
private:
int age;
char addr[20];
public:
void show( )
{ display( ); //引用基类的公用成员函数,允许。
cout<<"age,"<<age<<endl; //引用派生类的私有成员,正确。
cout<<"address,"<<addr<<endl;} //引用派生类的私有成员,正确。
};在派生类成员函数show中引用基类的公用成员函数display,通过display引用基类stud中的私有数据 num、name 和sex。可以这样写main函数(假设对象a中已有数据):void main( )
{student a;//定义一个student派生类的对象a

a.show( ); //输出a对象的5个数据
};
请分析在主函数中能否出现以下语句:
a.display( ); //正确。从基类继承的公用成员函数
a.age=18; //错误。外界不能引用派生类的私有成员
a.num=10020; //错误。外界不能引用基类的私有成员