//头文件
#include<string>
using namespace std;
class People
{
public:
People():name(""){}
virtual double height() const =0;
virtual void job() =0;
virtual People* copy() const =0;
virtual ~People(){}
private:
int id;
std::string name;
};
class Stu:public People
{
public:
double height() const
{
cout<<"高度"<<endl;
return 0;
}
void job()
{
cout<<"学生"<<endl;
}
People* copy() const
{
return new Stu(*this);
}
virtual ~Stu(){}
string School();
private:
string shool;
};
class Tea:public People
{
public:
double height() const
{
cout<<"教师高度"<<endl;
return 0;
}
void job()
{
cout<<"教师"<<endl;
}
People* copy() const
{
return new Tea(*this);
}
virtual ~Tea(){}
private:
string shool;
};
class Agent
{
public:
Agent():vp(0){} //允许声明指针数组
Agent(const People &v):vp(v.copy()){}
virtual ~Agent(){delete vp;}
Agent(const Agent& v):vp(v.vp?v.vp->copy():0){}
void job()
{
if(vp==0)
throw "不存在这个对象";
vp->job();
}
Agent& operator=(const Agent& v)
{
if(this!=&v)
{
delete vp;
vp=(v.vp?v.vp->copy():0);
cout<<"等号的析构"<<endl;
}
return *this;
}
private:
People * vp;
};
#include<iostream>
#include"head.h"
using namespace std;
int main()
{
Stu a;
Tea b;
People* ptr[100];
ptr[0]=&a;
ptr[1]=&b;
ptr[0]->job();
ptr[1]->job();
Agent agent[10];
agent[0]=Agent(a);
agent[1]=Agent(b);
agent[0].job();
agent[1].vp->job();
agent[1].job();
return 0;
}