#include <iostream>
using namespace std;
class person
{
public:
person()
{
cout<<"person()"<<endl;
}
~person()
{
cout<<"~person()"<<endl;
}
void eat()
{
name = "hhhhhh";
age = 24;
cout<<"eat()"<<endl;
}
protected:
string name;
private://父类的私有成员虽然被继承,但是无法使用
int age;
};
class worker:public person//公有继承,继承了person,person是基类,worker是派生类
{
public:
worker()
{
cout<<"worker()"<<endl;
}
~worker()
{
cout<<"~worker()"<<endl;
}
void work()
{
name = "1111";//protected能访问
//age = 3;//编译错误,因为是父类的私有成员
cout<<"work()"<<endl;
}
int salary;
};
int main()
{
/*
worker *p = new worker;//创建的时候先创建基类,再创建派生类
p->name = "ya";
p->eat();//继承之后可以访问基类的数据和函数
p->work();//也可以访问自己的数据和函数
delete p;//销毁的时候先销毁派生类,再销毁基类
p = NULL;
cout<<endl;
*/
/*
person zs;
zs.eat();//private数据自己能访问
zs.name;
*/
}
C++公有继承
最新推荐文章于 2021-04-14 19:51:56 发布