【任务1】理解基类中成员的访问限定符和派生类的继承方式
#include <iostream>
using namespace std;
#include <string>
class Student //(1)修改student类中各数据成员和成员函数的访问限定符,并观察发生的现象
{
public:
Student(int n,string nam,char s) ;
void show();
~Student(){ }
protected: //当访问限定符是private时出现错误
int num;
string name;
char sex ;
};
class Student1:protected Student //(2)修改此处的继承方式,并观察发生的现象
{ public:
Student1(int n,string nam,char s,int a,string ad):Student(n,nam,s)
{ age=a;
addr=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;
}
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;
}
修改一: 将public的student中的public改为protected出现错误。 原因是基类student的void show()函数变成了受保护的类型,只能在派生类以及派生类的下级使用,而 不能在基类以及派生类外使用。
修改二: 将public的student中的public改为private出现错误。 原因是基类student的void show()函数变成了私有的类型,不能在派生类以及派生类的下级使用,只能在 基类中使用。
修改三: 派生类的继承方式改为private出现错误。 原因是私有继承基类的公用成员和保护成员在派生类中成了私有类型。说明私有成员函数和受保护成员函数一 样,都不能被对象直接调用。
修改四: 派生类的继承方式改为protected出现错误。 原因保护成员不能被对象直接调用。