0

我正在将一个数组传递给我的类,我正在构建它,然后我能够进行事务处理(用新数据替换数组)或添加事务处理(因此,如果数组的第一个大小为 10,那么另外 10 个被添加到让它有 20 个元素,数组中的数量可能并不总是 20 等)

当使用前两种方法而不是添加事务方法时,代码会产生我期望的正确结果。没有按预期添加另外 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;
 }
4

3 回答 3

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如前所述,您还应该编辑。

于 2013-03-13T15:39:49.163 回答
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;

 }
于 2013-03-13T15:27:38.287 回答
0

你错过了这条线

nTransactions = numTransactions;

在您的 setTransactions 中。您的构造函数应该简单地调用您的 setTransactions 方法,因此您只有一次该代码。

于 2013-03-13T15:27:53.787 回答