嘿,执行代码后,我的代码说“帐户”已损坏...

这是什么意思,我该如何解决?

#include <iostream>
#include <iomanip>

using namespace std;

class BankAccount
{
private:
    int accountNum;
    double accountBal;
    const static double annualIntRate;
public:
    void enterAccountData(int, double);
    //void computeInterest();
    //void displayAccount();
};

// implementation section:
//const double BankAccount::annualIntRate = 0.03;
void BankAccount::enterAccountData(int number, double balance)
{
    cout << setprecision(2) << fixed;
    accountNum = number;
    accountBal = balance;

    cout << "Enter the account number " << endl;
    cin >> number;

    while(number < 0 && number <= 999)
    {
        cout << "Account numbers cannot be negative or less than 1000 " <<
                "Enter a new account number: " << endl;
        cin >> number;
    }

    cout << "Enter the account balance " << endl;
    cin >> balance;

    while(balance < 0)
    {
        cout << "Account balances cannot be negative. " <<
                "Enter a new account balance: " << endl;
        cin >> balance;
    }
    return;
}
/*void BankAccount::computeInterest()
{

}*/

int main()
{
    const int QUIT = 0;
    const int MAX_ACCOUNTS = 10;
    int counter;
    int input;
    int number = 0;
    double balance = 0;

    BankAccount accounts[MAX_ACCOUNTS];
    //BankAccount display;
    do
    {
        counter = 0;
        accounts[MAX_ACCOUNTS].enterAccountData(number, balance);
        cout << " Enter " << QUIT << " to stop, or press 1 to proceed.";
        cin >> input;
        counter++;
    } while(input != QUIT && counter != 10);

    system("pause");
    return 0;
}

最佳答案

enterAccountData()中,应在使用accounts[MAX_ACCOUNTS]时使用accounts[counter]
MAX_ACCOUNTS索引超出数组的范围(一个),导致在检索它时发生不可预测的行为(它将在数组之后立即读取内存中的任何内容,并尝试将其刺入BankAccount对象)。

另外,由于您要在循环内将counter初始化为0,因此每次将其重新初始化。您想要将该初始化移至循环开始之前。

关于c++ - “corrupted”在程序结尾,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5284378/

10-12 20:05