#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();
// }
}
对象的创建、回收、new和malloc
最新推荐文章于 2022-03-01 11:02:44 发布