我正在将数组传递给我的类,我正在构建它,然后我有能力进行事务处理(用新数据替换数组)或添加事务(所以如果数组首先是10号,那么另外10个是添加它使它有20个元素,数组中的数量可能不总是20等)
在使用前两种方法而不是add transaction方法时,代码会产生正确的结果。它没有按预期添加另外10个元素
有人知道我们在编码中遇到了什么问题吗?
我受这个任务结构的约束,所以使用可用的结构是理想的。
Transaction* tArray;
int nTransactions;
Analyser::Analyser(Transaction* transactions, int numTransactions)
{
//contructs the array and the amount of transations
tArray = transactions;
nTransactions = numTransactions;
}
void Analyser::setTransactions(Transaction* transactions, int numTransactions)
{
//set tArray to new set of transactions
tArray = transactions;
}
void Analyser::addTransactions(Transaction* transactions, int numTransactions)
{
Transaction* newT;
newT = new Transaction[numTransactions + nTransactions];
for(int i = 0; i<nTransactions; i++)
{
newT[i] = tArray[i];
}
for (int j = nTransactions; j<numTransactions + nTransactions; j++ )
{
newT[j] = transactions[j-nTransactions];
}
tArray = newT;
}
答案 0 :(得分:0)
你应该这样做:
void Analyser::setTransactions(Transaction* transactions, int numTransactions)
{
//set tArray to new set of transactions
tArray = transactions;
ntransactions = numTransactions //HERE YOU NEED TO UPDATE THIS TOO
}
正如评论中所述,也在这里:
void Analyser::addTransactions(Transaction* transactions, int numTransactions)
{
nTransactions += numTransactions;
Transaction* newT;
newT = new Transaction[nTransactions]; //Enough for all transactions
for(int i = 0; i< nTransactions; i++)
{
newT[i] = tArray[i];
}
for (int j = 0; j< numTransactions; j++ )
{
newT[nTransactions - numTransactions + j] = transactions[j];
}
tArray = newT;
}
答案 1 :(得分:0)
你错过了这一行
nTransactions = numTransactions;
在你的setTransactions中。你的构造函数应该只调用你的setTransactions方法,所以你只需要一次代码。
答案 2 :(得分:0)
您的addTransactions
代码应如下所示:
void Analyser::addTransactions(Transaction* transactions, int numTransactions)
{
Transaction* newT;
newT = new Transaction[numTransactions + nTransactions];
for(int i = 0; i<nTransactions; i++)
{
newT[i] = tArray[i];
}
for (int j = nTransactions; j<numTransactions + nTransactions; j++ )
{
newT[j] = transactions[j-nTransactions];
}
delete[] tArray;
tArray = newT;
nTransactions += numTransactions;
}
delete[] tArray
确保您没有泄漏任何记忆。在这种情况下,我假设Analyzer始终拥有tArray,即使在构造函数和setTransactions
中仅使用给定指针时也是如此。
nTransactions += numTransactions;
确保tArray
的大小得到适当更新。您还应该如前所述编辑setTransactions
。