C++中的代理类

//头文件
#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;
}


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值