//原代码
#include <iostream>
using namespace std;
class StudentA //(1)修改studentA类中各数据成员和成员函数的访问限定符,并观察发生的现象
{
public:
StudentA(int n,string nam,char s);
void showA();
~StudentA( ) { }
protected:
int num;
string name;
char sex ;
};
class StudentB: public StudentA //(2)修改此处的继承方式,并观察发生的现象
{
public:
StudentB(int n,string nam,char s,int a,string ad);
void showB( );
~StudentB( ) { }
private:
int age;
string addr;
};
StudentA::StudentA(int n,string nam,char s)
{
num=n;
name=nam;
sex=s;
}
void StudentA::showA()
{
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl<<endl;
}
StudentB::StudentB(int n,string nam,char s,int a,string ad):StudentA(n,nam,s)
{
age=a;
addr=ad;
}
void StudentB::showB( )
{
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl;
cout<<"age: "<<age<<endl;
cout<<"address: "<<addr<<endl<<endl;
}
int main( ) //(3)思考由于访问限定符和继承方式的改变,会引发什么现象的发生,并作出解释
{
StudentB stud1(10010,"Wang-li",'f',19,"115 Beijing Road,Shanghai");
StudentB stud2(10011,"Zhang-fun",'m',21,"213 Shanghai Road,Beijing");
StudentA stud3(20010,"He-xin",'m');
stud1.showB( );
stud2.showA( );
stud3.showA( );
return 0;
}
//修改后的
#include <iostream>
#include <string>
using namespace std;
class StudentA //(1)修改studentA类中各数据成员和成员函数的访问限定符,并观察发生的现象
{
public:
StudentA(int n,string nam,char s);
void showA();
~StudentA( ) { }
protected:
int num;
string name;
char sex ;
};
class StudentB: public StudentA //(2)修改此处的继承方式,并观察发生的现象
{
public:
StudentB(int n,string nam,char s,int a,string ad);
void showB( );
~StudentB( ) { }
private:
int age;
string addr;
};
StudentA::StudentA(int n,string nam,char s)
{
num=n;
name=nam;
sex=s;
}
void StudentA::showA()
{
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl<<endl;
}
StudentB::StudentB(int n,string nam,char s,int a,string ad):StudentA(n,nam,s)
{
age=a;
addr=ad;
}
void StudentB::showB( )
{
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl;
cout<<"age: "<<age<<endl;
cout<<"address: "<<addr<<endl<<endl;
}
int main( ) //(3)思考由于访问限定符和继承方式的改变,会引发什么现象的发生,并作出解释
{
StudentB stud1(10010,"Wang-li",'f',19,"115 Beijing Road,Shanghai");
StudentB stud2(10011,"Zhang-fun",'m',21,"213 Shanghai Road,Beijing");
StudentA stud3(20010,"He-xin",'m');
stud1.showB( );
stud2.showA( );
stud3.showA( );
return 0;
}
将StudentA中的potected改为public并不影响结果,但是若改为private则会出错。
将class StudentB: public StudentA中的public改为protected则会出错。