我对在 C++ 中处理对象数组有点困惑,因为我似乎无法找到有关它们如何传递(引用或值)以及它们如何存储在数组中的信息。
我希望一个对象数组是一个指向该对象类型的指针数组,但我还没有发现这个写在任何地方。它们会是指针,还是对象本身会以数组的形式排列在内存中?
在下面的示例中,自定义类 myClass 包含一个字符串(这是否会使其具有可变大小,或者字符串对象是否包含指向字符串的指针,因此占用了一致的空间量。我尝试创建一个动态数组myContainer 中的 myClass 对象。在 myContainer.addObject() 方法中,我尝试创建一个更大的数组,将所有对象与新对象一起复制到其中,然后删除旧对象。我完全不相信我我用我的析构函数正确清理我的内存——我可以在这方面做些什么改进?
class myClass
{
private:
string myName;
unsigned short myAmount;
public:
myClass(string name, unsigned short amount)
{
myName = name;
myAmount = amount;
}
//Do I need a destructor here? I don't think so because I don't do any
// dynamic memory allocation within this class
};
class myContainer
{
int numObjects;
myClass * myObjects;
public:
myContainer()
{
numObjects = 0;
}
~myContainer()
{
//Is this sufficient?
//Or do I need to iterate through myObjects and delete each
// individually?
delete [] myObjects;
}
void addObject(string name, unsigned short amount)
{
myClass newObject = new myClass(name, amount);
myClass * tempObjects;
tempObjects = new myClass[numObjects+1];
for (int i=0; i<numObjects; i++)
tempObjects[i] = myObjects[i]);
tempObjects[numObjects] = newObject;
numObjects++;
delete newObject;
//Will this delete all my objects? I think it won't.
//I'm just trying to delete the old array, and have the new array hold
// all the objects plus the new object.
delete [] myObjects;
myObjects = tempObjects;
}
};