#include<iostream>
#include<string>
using namespace std;
class Student //(1)修改student类中各数据成员和成员函数的访问限定符,并观察发生的现象
{
public:
Student(int n,string nam,char s) ;
void show();
~Student( ){ }
protected:
int num;
string name;
char sex ;
};
class Student1: public Student //(2)修改此处的继承方式,并观察发生的现象
{
public:
Student1(int n,string nam,char s,int a,string ad);
void show1( );
~Student1( ){ }
private:
int age;
string addr;
};
Student::Student(int n,string nam,char s)
{
num=n;
name=nam;
sex=s;
}
void Student::show()
{
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl<<endl;
}
Student1::Student1(int n,string nam,char s,int a,string ad):Student(n,nam,s)
{
age=a;
addr=ad;
}
void Student1::show1( )
{
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl;
cout<<"age: "<<age<<endl;
cout<<"address: "<<addr<<endl<<endl;
}
int main( )
{
Student1 stud1(10010,"Wang-li",'f',19,"115 Beijing Road,Shanghai");
Student1 stud2(10011,"Zhang-fun",'m',21,"213 Shanghai Road,Beijing");
Student stud3(20010,"He-xin",'m');
stud1.show1( );
stud2.show( );
stud3.show( );
system("pause");
return 0;
}
1.把class Student1: public Student改为private Student,提示错误:'show' : cannot access public member declared in class 'Student'!
则Student类里的成员函数void show();变成私有函数,禁止Student类外的对象访问。
2.把Student中的 public Student 改为protected Student,出现3个错误,1.'Student::Student' : cannot access protected member declared in class 'Student'! 2.'Student::~Student' : cannot access protected member declared in class 'Student'! 3.'show' : cannot access protected member declared in class 'Student'!
3.把class Student1: public Student改为protected Student,提示错误:'show' : cannot access public member declared in class 'Student'!
说明Student类里的成员函数void show();变成了受保护类型的,不允许Student类的对象直接访问。
1.派生类中访问属性为public的成员在派生类内部和外部都可以访问。
2.派生类中访问属性为private的成员在派生类内部可以访问,在派生类外部不可以访问。
3.派生类中访问属性为protected的成员在派生类内部可以访问,在派生类外部不可以访问。
num: 10010
name: Wang-li
sex: f
age: 19
address: 115 Beijing Road,Shanghai
num: 10011
name: Zhang-fun
sex: m
num: 20010
name: He-xin
sex: m
请按任意键继续. . .