三种继承模式
在上图中: 派生==继承
三种继承模式
protected模式中
父类的公有属性和保护属性的成员在子类中都会变为保护属性,只能通过父类或者子类的成员函数调用.
代码示例:
#include <iostream>
#include <string>
using namespace std;
//protected
class person{public :person(){}person(int num,string name ,int age):num(num),name(name),age(age){}protected: void print(){cout<<num<<name<<"----"<<age<<endl;}private:int num;string name;int age;
};class worker:protected person{public:worker(){}worker(int num,string name,int age ,double salary):person(num,name,age),salary(salary){}//父类的私有成员,只能通过继承来的父类的成员函数访问 ,比如子类的构造函数中调用父类的构造函数构造了person类的对象.//父类的私有成员的初始化应该交给父类的构造函数.double getsalary(){return salary;}void show(){ //调用父类的protected属性的函数print();}private:double salary;
};int main(){worker w1(1,"lucy",21,11100);//w1.print();//子类调用父类的函数cout<< w1.getsalary()<<endl;w1.show();
}