对象的创建、回收、new和malloc

#include <iostream>
using namespace std;
#include <stdio.h>
#include <iostream>

class object
{
public :
     object();
     ~object();
     virtual int hit()=0;
};
 object::object()
{
   // printf("object\n");
    int x = 5;
}
 object::~object()
{
    //printf("zz\n");
}
class sphere : public object
{
public:
     sphere();
     ~sphere();
     int hit();
};
 sphere::sphere()
{
   // printf("ss\n");
}
 int sphere::hit()
{
    return 49;
}
 sphere::~sphere()
{
    printf("deconstrust\n");
}

class cube : public object
{
  public:
    sphere* s;
     cube();
     ~cube();
     int hit();
};
 cube::cube()
{

}
 cube::~cube()
{

}
 int cube::hit()
{
    return s->hit();
}

 int AddHit(object* o, object* t)
{
    return o->hit() + t->hit();
} 
 void  add(sphere *s )
{
    object* o[2];
    o[0] = &s[0];
    o[1] = &s[1];
    int x =  o[0]->hit() + o[1]->hit();
    printf("x = %d\n",x);
}
int main(int argc, char *argv[])
{
    //1.如果采用1的方式,程序会崩溃,我的理解是,这里只是进行了malloc的操作,
    //只是分配了内存,但是还有一些其他的初始化操作没有进行,所以需要改为用2的方式
    //new不仅进行了内存分配,还搞了别的必须要做的事情,多看看new和malloc的区别。
    //sphere* s_temp = (sphere*)malloc( sizeof(sphere) * 5);

    //2
    sphere world_host[ 5 ] =
    {
        sphere(),
        sphere(),
        sphere(),
        sphere(),
        sphere()
    };
    add(world_host );

    //还要注意,这里回收这个对象数组,不要用delete。有new才有delete,一定是配对的!
    //如果是new出来的对象,那么就要用delete的方式回收。
    //创建对象的三种方法:
    //A a(1);            //栈中分配
    //A b = A(1);        //栈中分配
    //A* c = new A(1);   //堆中分配
    //delete c;
    //如果是new了n个对象出来(对象数组),那么回收的时候,如果只是delete 对象名,这样会导致内存泄漏,
    //因为光是对象名的话,就只是delete了数组中第一个对象,
    //正确的: delete[n] 对象名;
    //不必显示调用析构函数,默认调用的
//    for(int i = 0;i < 5 ; i++)
//    {
//        world_host[i].~sphere();
//    }
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值