C++ 的三种访问权限与三种继承方式的三种访问权限与三种继承方式
我们知道C++中的类,有三种访问权限(也称作访问控制),它们分别是public、protected、private,C++中继承
的方式还有多种。下面通过本文给大家详细介绍,对c++中的访问权限和继承方式感兴趣的朋友一起看看吧
三种访问权限三种访问权限
我们知道C++中的类,有三种访问权限(也称作访问控制),它们分别是public、protected、private。要理解它们其实也很容
易,看下面了一个例子。
父类:父类:
class Person
{
public:
Person(const string& name, int age) : m_name(name), m_age(age)
{
}
void ShowInfo()
{
cout << "姓名:" << m_name << endl;
cout << "年龄:" << m_age << endl;
}
protected:
string m_name; //姓名
private:
int m_age; //年龄
};
class Person
{
public:
Person(const string& name, int age) : m_name(name), m_age(age)
{
}
void ShowInfo()
{
cout << "姓名:" << m_name << endl;
cout << "年龄:" << m_age << endl;
}
protected:
string m_name; //姓名
private:
int m_age; //年龄
};
子类:子类:
class Teacher : public Person
{
public:
Teacher(const string& name, int age, const string& title)
: Person(name, age), m_title(title)
{
}
void ShowTeacherInfo()
{
ShowInfo(); //正确,public属性子类可见
cout << "姓名:" << m_name << endl; //正确,protected属性子类可见
cout << "年龄:" << m_age << endl; //错误,private属性子类不可见
cout << "职称:" << m_title << endl; //正确,本类中可见自己的所有成员
}
private:
string m_title; //职称
};
class Teacher : public Person
{
public:
Teacher(const string& name, int age, const string& title)
: Person(name, age), m_title(title)
{
}
void ShowTeacherInfo()
{
ShowInfo(); //正确,public属性子类可见
cout << "姓名:" << m_name << endl; //正确,protected属性子类可见
cout << "年龄:" << m_age << endl; //错误,private属性子类不可见
cout << "职称:" << m_title << endl; //正确,本类中可见自己的所有成员
}