我知道我可以使用名为 std::vector
的东西,但由于类(class)限制,我担心这是不可能的。
我需要制作一个动态可扩展的对象数组。当需要存储新对象时,数组应该不断增长。
这是数组所属的类:
class TransactionList
{
private:
Transaction *trans;
int amountTransactions;
Transaction newTrans;
public:
TransactionList();
~TransactionList();
void read( istream &is );
void write( ostream &os );
void add( Transaction & newTrans );
double totalExpenses();
double hasPaid( string namnet );
double isDebted( string namnet );
//PersonList FixPersons();
};
方法“void add (Transaction & newTrans)”是我需要的方法。是的,我真的必须以指针方式来做。
到目前为止,这种方法是完全不完整的,甚至还远未达到功能性。我尝试了几种不同的方法,但最终会出现运行时错误或只是胡说八道的结果。
void TransactionList::add(Transaction & newTrans)
{
Transaction* tempArrPtr;
amountTransactions++;
trans = new Transaction[amountTransactions]
trans[amountTransactions - 1] = newTrans;
}
我想要该方法做的是构建一个事务对象数组,并在获取更多对象时增加大小。
我希望我已经清楚地写下了我的问题,并希望有人能给我一个好的答案。 我试过谷歌搜索,但我仍然卡住了 - 否则我不会费心去问 :p
此外,如果有人可以提供一些有关复制构造函数的指示,我将不胜感激。在我们的类(class) Material 中,他们几乎没有展示复制构造函数应该是什么样子。就像“深度复制需要复制构造函数,祝你好运!”
最佳答案
你应该添加一个 maxTransactions
变量,它会指示你的 trans* 数组的分配长度,并初始化 ammountTransactions
和 maxTransactions
0.
当我们达到 trans 的限制时,您的数组会自动将其大小加倍
void TransactionList::add(Transaction & newTrans)
{
if(amountTransactions == maxTransactions){ //we've reached the capacity of trans
//allocate a new array
Transaction* nuTrans = new Transaction[maxTransactions*2+1];
//copy the old values of trans into nuTrans
memcpy(nuTrans, trans, sizeof(Transaction)*maxTransactions);
//deallocate the old trans array
delete []trans;
//set trans to point at your newly allocated array
trans = nuTrans;
//update maxTransactions
maxTransactions = maxTransactions*2+1;
}
trans[amountTransactions] = newTrans;
amountTransactions++;
}
附言。我这里直接写了,是整体编译还是没调试代码我没检查。但我将其作为您可以遵循的想法呈现
编辑:工作示例@ http://ideone.com/uz1mE
关于c++ - 对象的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6239169/