C++:当我尝试访问私有 class 字符串变量时程序崩溃。为什么会这样,我该如何解决?

C++: Program crashes when I try to access a private class string variable. Why is this, and what can I do to fix it?

我正在编写一个为用户提供菜单系统的银行账户程序,允许他们在 4 个选项之间进行选择:A) 添加客户,B) 打印所有客户数据,C) 更新客户数据,以及D) 退出程序。每个选项执行单独的任务。 本题我关注的选项是选项A

选项A应该生成一个新的银行账户对象,并要求用户输入账户持有人姓名、账户的初始存款(新账户的初始存款额)和利率.然后它需要将这些值设置为任何给定对象的 bankAccount class 中的正确私有值。

选项 B 之前 main.cpp 的代码(此后有更多代码,因此末尾没有后括号,但我想尽量保持简洁):

#include <iostream>
#include <string>
#include <cstdlib>
#include "header.h"
#include "implementation.cpp"

using namespace std;

int main()
{
    //array of bankAccount class objects (up to 20)
    bankAccount account[20];
    string menuInput = "";           //used for menu loop input
    string accNameInput = "";        //used for account customer name user input
    float depositInput = 0;   //used for initial deposit input
    float interestInput = 0;  //used for initial interest input
   // int customerCount = 0;    //used to compare to static int to determine # of customers in memory

    int static i = 0;

    //while loop keeps user in the menu until they choose to exit program

    while (true)
    {

    cout << endl << "Enter a letter option below: "
        << endl << endl << "A: Add a customer" << endl << "B: Print all customer data available"
        << endl << "C: Update customer data" << endl << "D: End program" << endl << endl;

    cin >> menuInput;

 //Option A: Add a customer
 if (menuInput == "A" || menuInput == "a")
 {
     //checking for max customer limit
    if (i > 19)
    {
        cout << endl << "Cannot add customer; Max customer capacity reached." << endl;
    }
    else //
     {
        ///Creates a new customer account and asks for new customer name,
        ///initial deposit amount, & interest
       cout << endl << "Bank account #" << (i + 1) << " created." << endl;
       bankAccount account[i];     //new bank account object created

        //time to set the name for our new customer...
       cout << endl << "Enter customer name for account #" << (i + 1) << ": " << endl;
       cin >> accNameInput;


       //setting initial deposit amount
       cout << endl << "Enter initial deposit amount for account #" << (i + 1) << ": " << endl;
       cin >> depositInput;


       //setting initial interest rate
       cout << endl << "Enter interest rate (without % sign): " << endl;
       cin >> interestInput;


 account[i].setInterestRate(interestInput);
 account[i].setBalance(depositInput);
 account[i].setAccountHolderName(accNameInput);


        //increments the account number counter
        i++;
     }
 }

在此处的最后一行找到的 setAccountHolderName() 问题仍然存在:

account[i].setInterestRate(interestInput);
account[i].setBalance(depositInput);
account[i].setAccountHolderName(accNameInput);

当我调用 class 函数 setInterestRate 和 setBalance 将输入值设置为它们各自的私有 class 变量时,程序像往常一样进行,并将用户带回主菜单应该。 但是调用 setAccountHolderName 会使程序崩溃并且 returns 这个值:-1073741819 (0xC0000005).

我将在下面包含头文件和实现文件中的一些代码,以展示我如何编写 accountHolderName 代码:

header.h(包括 accountHolderName get/set 函数):

///Name of file: header.h
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <iostream>
#include <string>

using namespace std;

class bankAccount
{
    //private data values
    string accountHolderName;
    int accountNumber;
    //static int accCounter;  //keeps track of account numbers
    float balance;
    float interestRate;

public:

    //Default constructor
    bankAccount();

    ///Getters/setters for all private member variables
    //accountNumber
    int getAccountNumber();
    void setAccountNumber(int accNum);

    //accountHolderName
    string getAccountHolderName();
    void setAccountHolderName(string accName);

implementation.cpp(包括 accountHolderName 实现):

///Name of file: implementation.cpp
#include <iostream>
#include <string>
#include "header.h"

using namespace std;

//static int definition (guess you have to define static members here?)
//int bankAccount::accCounter;

//Default constructor
bankAccount::bankAccount()
{
    accountHolderName = "";
    accountNumber = 0;
   // accCounter = 0;
    balance = 0;
    interestRate = 0;
}

    ///Getters/setters for all private member variables
    //accountNumber
int bankAccount::getAccountNumber()
{
    return accountNumber;
}
void bankAccount::setAccountNumber(int accNum)
{
    accountNumber = accNum;
}

    //accountHolderName
string bankAccount::getAccountHolderName()
{
    return accountHolderName;
}
void bankAccount::setAccountHolderName(string accName)
{
    accountHolderName = accName;
}

似乎在某些方面搞乱了代码(例如完全删除选项 A 代码之后的代码,在默认构造函数中注释掉 accountHolderName = ""; 等)将暂时允许 account[i].setAccountHolderName(accNameInput); 在不使程序崩溃的情况下运行,但这非常不一致,让我更加困惑。我不确定这个问题是否与内存有关或什么。我还尝试使用 cout 来查看来自 main.cpp 的输入变量 accNameInput 是否被存储到,它是。

抱歉,如果这只是代码过多或解释过多;这是我的第一个 post,我只是想提供我的大部分代码,这样您就可以看到全部内容。 我在这里要做的就是访问 bankAccount class 私有字符串变量 accountHolderName,并将用户输入存储到每个新对象中 .

我试着在线解决这个问题,但似乎找不到任何有类似问题的东西。我不确定我错过了什么;任何帮助或指导将不胜感激。

从技术上讲,这一行:

bankAccount account[i];     //new bank account object created

在 C++ 中是不允许的,但一些编译器 (g++) 允许它作为扩展,因为它们在 C 编译器中正式支持变量堆栈数组。

此外,该声明覆盖了在更高范围内声明的同名变量

但是你会看到这些行:

account[i].setInterestRate(interestInput);
account[i].setBalance(depositInput);
account[i].setAccountHolderName(accNameInput);

但数组索引的有效范围为 0..i-1 所以你已经处于未定义的行为中,你的数组索引超出范围。

我怀疑你真的是这个意思:

bankAccount newAccount;     //new bank account object created

...

newAccount.setInterestRate(interestInput);
newAccount.setBalance(depositInput);
newAccount.setAccountHolderName(accNameInput);

account[i] = newAccount;
i++;