2-1 为什么继承
内存中的对象:
2-2 代码演示
Person.h
#include <string>
using namespace std;//class也在std里面
class Person
{
public:
Person();
~Person();
void eat();
string m_strName;
int m_iAge;
};
Person.cpp
#include "Person.h"
#include <iostream>
using namespace std;
Person::Person()
{
cout<<"Person()"<<endl;
}
Person::~Person()
{
cout<<"~Person()"<<endl;
}
void Person::eat()
{
cout<<"eat()"<<endl;
}
Worker.h
#include "Person.h"
class Worker:public Person //公有继承
{
public:
Worker();
~Worker();
void work();
int m_iSalary;
};
Worker.cpp
#include <iostream>
#include "Worker.h"
using namespace std;
Worker::Worker()
{
cout<<"Worker()"<<endl;
}
Worker::~Worker()
{
cout<<"~Worker()"<<endl;
}
void Worker::work()
{
cout<<"work()"<<endl;
}
demo.cpp
#include <iostream>
#include <stdlib.h>
#include "Worker.h"
using namespace std;
int main()
{
Worker *p = new Worker();
p->m_strName = "Jim";
p->m_iAge = 10;
p->eat();
p->m_iSalary = 10000;
p->work();
delete p;
p = NULL;
system("pause");
return 0;
}
运行结果
Person()
Worker()
eat()
work()
~Worker()
~Person()
请按任意键继续. . .