【发布时间】:2017-01-19 02:44:48
【问题描述】:
如何在不使用向量的情况下调整数组的大小? 我要调整大小的数组是指向类的指针
class A
{
private:
B * b;
int numOfItems;
int maxNumOfItems;
public:
A();
~A();
resizeMX();
};
A::A()
{
numOfItems = 0;
maxNumOfItems = 20;
b = new B[maxNumOfItems];
for(int i=0;i<maxNumOfItems ;i++)
{
b[i] = 0;
}
}
A::~A()
{
for(int i=0;i<numOfItems;i++)
{
delete [] b;
}
}
void A::resizeMX(const B & obj)
{
bool value=false;
if(numOfItems<=maxNumOfItems && value == false)
{
//assign values to *b in for loop
}
else
{
//resize index of *b
我知道我们应该动态分配新内存。像这样?
++maxNumOfItems;
b=new B[maxNumOfItems];
//keep previous assigned values and add new values at the end
for(int j=numOfItems;j<maxNumOfItems;j++)
{
//assign values to b[j]
}
}
numOfItems++;
}
假设我确实重载了 = 运算符
【问题讨论】:
-
你是
~A()应该只调用一次删除。delete [] b;
标签: c++ class dynamic-memory-allocation