在 C++ 中,一旦声明就没有调整数组大小的概念。动态数组也是如此,一旦分配就无法调整大小。但是,您可以创建一个更大的数组,将旧数组中的所有元素复制到新数组中,然后删除旧数组。这是不鼓励的,并且不会有效。
Usingstd::vector
将允许您随意添加,并且还将跟踪其大小,因此您不需要count
作为课程的一部分。
class B
{
// no need to allocate, do add when required i.e. in B::add
B() : count(), elements() { }
A add(A place)
{
// unnecessarily allocate space again
A *new_elements = new A[count + 1];
// do the expensive copy of all the elements
std::copy(elements + 0, elements + count, new_elements);
// put the new, last element in
new_elements[count + 1] = place;
// delete the old array and put the new one in the member pointer
delete [] elements;
elements = new_elements;
// bunp the counter
++count;
return place; //redundant; since it was already passed in by the caller, there's no use in return the same back
}
protected:
size_t count;
A *elements;
};
上面的代码可能会做你想要的,但非常不鼓励。使用向量;你的代码将简单地变成
class B
{
// no need of a constructor since the default one given by the compiler will do, as vectors will get initialized properly by default
void Add(A place)
{
elements.push_back(place);
// if you need the count
const size_t count = elements.size();
// do stuff with count here
}
protected:
std::vector<A> elements;
};