private与protected:
区别:
派生之后,private对应的基类的私有数据成员在派生类当中是无法进行访问的,但protected对应的基类的私有数据成员在派生类当中是可以进行访问的。
共同点:
private与protected的数据成员都只能够在类内访问,类外无法访问,
#include<iostream>
#include<string>
using namespace std;
class Person
{
protected:
string Name;//姓名
int Age;//年龄
int ID;//学号
private:;
public:
Person(const string& Strname, const int StrAge = 18, const int StrID = 00000) : Name(Strname), Age(StrAge), ID(StrID){};
void ShowInf()
{
cout << "个人类:" << endl;
cout <<"姓名:"<< Name << endl;
cout <<"年龄:"<< Age << endl;
cout << "学号:" << ID << endl << endl;
};
int GetAge(){ return Age; }
};
class Teacher:virtual public Person//虚基类继承
{public:
//派生类的构造函数
Teacher(const string& Strname, const int StrAge = 18, const int StrID = 00000, const string& StrClass="计算机") :Class(StrClass), Person(Strname, StrAge, StrID){}
void ShowInf()
{
cout << "教师类:" << endl ;
cout << "姓名:" << Name << endl;
cout << "年龄:" << Age << endl;
cout << "学号:" << ID << endl;
cout << "教授课程:" << Class << endl << endl;
};
protected:
string Class;//教授课程名字
};
class PostgraguateStudent :virtual public Teacher
{
public:
PostgraguateStudent(const string& Strname, const int StrAge = 18, const int StrID = 00000, const string& StrClass = "计算机", const string StrGrade = "二") :Grade(StrGrade), Teacher(Strname, StrAge,StrID,StrClass), Person(Strname, StrAge, StrID){}
void ShowInf()
{
cout << "研究生类:" << endl ;
cout << "姓名:" << Name << endl;
cout << "年龄:" << Age << endl;
cout << "学号:" << ID << endl;
cout << "教授课程:" << Class << endl;
cout << "所在年级:" << Grade << endl;
};
private:
string Grade;//所在年级
};
int main(int argc, char* argv[])
{
Person person("shun",18,20231234);
person.ShowInf();
Teacher teacher("shun");
teacher.ShowInf();
PostgraguateStudent postgraguateStudent("xiaoming");
postgraguateStudent.ShowInf();//对基类当中的同名函数进行了隐藏
system("pause");
return 0;
}
运行结果:
个人类:
姓名:shun
年龄:18
学号:20231234
教师类:
姓名:shun
年龄:18
学号:0
教授课程:计算机
研究生类:
姓名:xiaoming
年龄:18
学号:0
教授课程:计算机
所在年级:二
请按任意键继续. . .