Public继承: 父类中public成员继承到子类中,在类外、类内都可以访问
父类中protected成员在子类类内是可以访问
Private继承:
父类中public成员继承到子类中,在类外不可以访问,类内部是可以访问
父类中private成员在子类类内是不可以访问的
父类中protected成员在子类类内是可以访问
Protected继承:
父类中public成员继承到子类中,在类外不可以访问,类内部是可以访问
父类中private成员在子类类内是不可以访问的
父类中protected成员在子类类内是可以访问
举例public继承
#include <iostream>
using namespace std;
#include <string>
//人类: 属性:姓名、性别、年龄 行为:吃、睡、show
//工人类:属性:姓名、性别、年龄、工资 行为:work
class Person
{
public:
Person(string name, string sex = "男", int age = 30) :name(name), sex(sex), age(age)
{
cout << "Person(string,string,int)" << endl;
}
~Person()
{
cout << "~Person" << endl;
};
void eat()
{
cout << this->name << "eat..." << endl;
}
void sleep()
{
cout << this->name << "sleep..." << endl;
}
void show()
{
cout << "姓名:" << this->name << "性别:" << this->sex << "年龄:" << this->age << endl;
}
protected:
string name;
string sex;
int age;
private:
};
class Worker :public Person
{
public:
Worker(string _name,string _sex = "男",int _age = 28,int _salary = 5000):Person(_name,_sex,_age),salary(_salary)
{
cout << "Worker(string,string,int,int)" << endl;
}
~Worker()
{
cout << "~Work()" << endl;
}
void work()
{
sleep();
eat();
show();
cout << name << endl;
cout << this->name<<"工作...." << endl;
}
void show()
{
cout << "姓名:" << this->name << "性别:" << this->sex << "年龄:" << this->age << "薪水"<<this->salary<<endl;
}
protected:
int salary;
private:
};
int main()
{
cout << sizeof(Person) << endl;
cout << sizeof(Worker) << endl;
Worker w("zhangsan");
w.show();
return 0;
}