【发布时间】:2018-09-10 00:16:45
【问题描述】:
我一直在从事一个项目,我应该在该项目中使用动态数组重新创建函数的基础。该程序应该有一个默认构造函数,它创建一个大小为 2 的数组,并且“向量”的大小为 0,直到将更多值添加到向量类中,命名为 DynArray。当数组已满时尝试 .push_back 进入向量时,我的程序应该制作一个容量为 2 倍的数组的新副本,并删除旧数组。这是我到目前为止所拥有的,我正在努力弄清楚应该如何设置复制构造函数以使其正常工作。
我一直在努力获取 push_back 和复制构造函数之间跳跃 当我同时撞到墙上时,工作正常。
#include <iostream>
using namespace std;
class DynArray
{
public:
DynArray();
DynArray(const DynArry& origClass);
~DynArray();
int capacity();
int size();
void push_back(int newNum);
int at(int atNum);
private:
int arraySize;
int arrayCapacity;
int newNum;
int pushCounter;
int atNum;
int i;
int arrayVector [];
};
DynArray::DynArray() // default constructor, creates array with no elements and capacity 2
{
int* arrayVector = new int[2];
arrayCapacity = 2;
arraySize = 0;
pushCounter = 0; // used for push_back, increments through array every time a new number is added with push_back
return;
}
DynArray::DynArray(const DynArray& origClass) // copy constructor
{
cout << "Copy Constructor Called." << endl;
int* arrayVector = new int[2];
*arrayVector = *(origClass.arrayVector)
return;
}
void DynArray::push_back(int newNum)
{
if (arraySize == arrayCapacity) // if the capacity is the same as the current size, make a new array with twice the capacity, copy over values, delete the old array
{
arrayCapacity = arrayCapacity * 2;
int* newarrayVector = new int[arrayCapacity];
for (i = 0; i < arraySize; ++i)
{
*newarrayVector [i] = arrayVector[i];
}
arrayVector [pushCounter] = newNum; // push value to the next open value in the array
++arraySize; // increment so next push_back uses the following value
++pushCounter;
}
【问题讨论】:
-
将复制构造函数中的大小设置为所需的大小。新的 int[orgClass.arrayCapacity]
-
复制构造函数需要复制整个数组,就像您的
push_back函数在分配新内存时所做的那样。此外,您可以从类声明中删除newNum,它是传递给您的函数的参数,不需要在那里声明。删除pushCounter并使用arraySize。 -
未来问题:没有赋值运算符。这打破了三法则,可以真正击中它的痛处。
-
这个问题目前的措辞基本上意味着您正在要求某人为您编写代码。更具体地说明你为什么挣扎。此外,您的代码中存在很多问题。
pushCounter没有用,因为它与arraySize做的事情完全相同。您有一个名为arrayVector的成员,它存储指向动态数组的指针,但是您随后在构造函数和push_back函数中声明了具有相同名称的局部变量。您还应该了解构造函数成员初始化列表,而不是为成员变量分配东西。 -
为什么你不能分配一个新数组并复制每个元素呢?
newNum和atNum是成员函数参数,而不是类成员。
标签: c++ constructor destructor copy-constructor