智能指针

C++对于内存的管理一直不是很好,稍不留心就会出现内纯泄露的错误。没有java的垃圾回收机制,写了一个代理类,实现指针的智能管理,这个算是智能指针的前身吧

头文件如下:

#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;cout<<"代理类的析构函数被执行"<<endl;}// 这个析构函数执行了多次 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); } return *this; } private: People * vp; };

main函数如下:

#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();
    return 0;
}

上面的例子都很简单,先定义一个人的类,然后学生和老师就继承这个人的类,

posted on 2013-05-20 12:32 HACKMIND 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/desheng-Win/archive/2013/05/20/3088360.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值