#include <cstdlib>
#include <iostream>
using namespace std;
const unsigned long MAX_SIZE = 20;
typedef int ItemType;
class Heap {
private:
ItemType array[MAX_SIZE];
int elements; //how many elements are in the heap
public:
Heap( )
~Heap( )
bool IsEmpty( ) const
bool IsFull( ) const
Itemtype Retrieve( )
void Insert( const Itemtype& )
};
假设我将这个作为我的头文件。在我的实现中,做Heap()构造函数和~Heap()析构函数的最佳方式是什么?
我有过
Heap::Heap()
{
elements = 0;
}
Heap::~Heap()
{
array = NULL;
}
我想知道在这种情况下,这是否是析构和构造数组的正确方法。
发布于 2009-12-10 16:25:17
array
不是动态分配的,因此当对象不再存在于作用域中时,它的存储空间就会消失。实际上,您不能将其重新赋值给array
;这样做是错误的。
发布于 2009-12-10 16:31:03
C++中有两种类型的数组:静态数组和动态数组。它们之间的主要区别在于如何为它们分配内存。静态数组或多或少是由编译器自动创建和销毁的。动态数组需要由程序员创建和销毁。您的对象当前使用静态数组,因此您无需担心它的创建或销毁。
但是,如果要将数组切换为动态数组,则可以按如下方式更改代码:
typedef int ItemType;
ItemType *array; // Pointer to location in memory where the array will reside.
Heap::Heap()
{
array = new ItemType[MAX_SIZE]; // Assign memory for the array to use.
elements = 0;
}
Heap::~Heap()
{
delete[] array; // Clear the memory used by the array.
}
发布于 2009-12-10 16:23:29
在dtor中不需要做任何事情,因此你不需要写一个。数组对象的内存不是动态分配的。因此,当Heap
对象超出作用域时,会自动释放为array
分配的内存。
https://stackoverflow.com/questions/1879431
复制相似问题