0

So basically what is going on is this. The code works perfectly fine to add the objects into the array. But when I close the accountFile, the entire array becomes NULL. How can I avoid this so that I can use the array for other things?

accounts = new Account*[numAccounts];

for (int i = 0; !accountFile.eof(); i++)
{
    if (accountFile >> tempAccountType)
    {
        if (tempAccountType == "Checking")
        {
            accountFile >> tempAccountNum >> tempBalance >> tempTransFee;
            CheckingAccount tempAccount(tempBalance, tempAccountNum, tempTransFee);
            accounts[i] = &tempAccount;
        }
        else
        {
            accountFile >> tempAccountNum >> tempBalance >> tempIntRate;
            SavingsAccount tempAccount(tempBalance, tempAccountNum, tempIntRate);
            accounts[i] = &tempAccount;
        }
    }
}
4

4 回答 4

1
std::vector<std::unique_ptr<Account>> accounts;

while(accountFile >> tempAccountType)
{
    if(tempAccountType == "Checking")
    {
        accountFile >> tempAccountNum >> tempBalance >> tempTransFee;
        accounts.emplace_back(new CheckingAccount(tempBalance, tempAccountNum, tempTransFee));
    }
    else
    {
        accountFile >> tempAccountNum >> tempBalance >> tempIntRate;
        accounts.emplace_back(new SavingsAccount(tempBalance, tempAccountNum, tempIntRate));
    }
}

1) 检查 !eof() 还不够好。我重组了循环

2) 使用向量

3) 使用智能指针(在本例中为 unique_ptr)

4) 不要存储指向本地范围对象的指针。你必须分配

于 2013-04-09T17:54:28.533 回答
1

问题不在于您关闭文件时,问题在于您正在对本地对象进行引用,当本地对象超出 socope 时该对象被破坏

首先,我将帐户定义为智能指针的向量

std::vector< shared_ptr<Account> > 

然后每次读取文件时创建一个新文件

accounts.push_back( make_shared<SavingsAccount)(tempBalance, tempAccountNum, tempTransFee);

只要向量存在,它就会存在。

于 2013-04-09T17:50:34.797 回答
1

由于您的对象的范围,会发生此错误。您的 tempAccount 对象在超出其范围时将被销毁。尝试这个:

//some stuff
if (tempAccountType == "Checking")
{
    accountFile >> tempAccountNum >> tempBalance >> tempTransFee;
    CheckingAccount *tempAccount=new CheckingAccount(tempBalance, tempAccountNum, tempTransFee);
    accounts[i]=tempAccount;
}
else
{
    accountFile >> tempAccountNum >> tempBalance >> tempIntRate;
    SavingsAccount *tempAccount=new SavingsAccount(tempBalance, tempAccountNum, tempIntRate);
    accounts[i] = tempAccount;
}
于 2013-04-09T17:51:28.923 回答
0

对象超出范围是因为它们是在 if 块中声明的。您通过引用保存它们,因此当它们超出范围时,引用变得无效。

尝试以下操作:

accounts[i] = tempAccount;

这将调用 for 的复制构造函数CheckingAccount,它将保存副本而不是引用。

于 2013-04-09T17:50:26.397 回答