【任务1】理解基类中成员的访问限定符和派生类的继承方式
由下面派生类Student1对基类Student的继承……
(1)请修改基类中成员的访问限定符和派生类的继承方式,考虑可能的运行结果或可能出现的错误,并在上机时进行验证、对比,达到理解派生类成员的访问属性的目的。
(2)总结(1)的结果,将(1)的结果摘要写到报告博文中;最后用自己的话总结确定派生类成员的访问属性的原则,也写到报告博文中。
(代码类似P363例11.5,上机准备阶段可以研究这段代码,BB平台中提供实验用代码。)
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):Student(n,nam,s) ;
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( );
return 0;
}
#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; } 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; } 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.派生类中访问属性为公用的成员在派生类内部和外部都可以访问。
2.派生类中访问属性为受保护的成员在派生类内部可以访问,在派生类外部不可以访问。
3.派生类中访问属性为私有的成员在派生类内部可以访问,在派生类外部不可以访问。