介绍银行账户类 - 奇怪的输出

Intro Bank Account Class - Strange Output

本文关键字:输出      更新时间:2023-10-16

这是为了类作业的介绍,我将创建一个银行账户,该账户能够通过存款或取款来操纵余额并查找账户余额。

我已经看了十几个不同的例子和操作方法,但现在我不知所措。

我从代码中获得的唯一输出是Account Balance: $-8589937190我不知道这个值从何而来。关于我应该从哪里开始的任何想法?

#include <iostream>
using namespace std;
// Define Account class
class Account
{
public:
    Account(int startingBal = 0){
        m_startingBal = startingBal;
}
void credit(int amount);
void withdraw(int amount);
int getBalance() const;
private:
int m_startingBal;
int balance;
};
void Account::credit(int amount)    // deposit money
{
balance += amount;
};
void Account::withdraw(int amount)  // withdraw money
{
balance -= amount;
};
int Account::getBalance() const     // return the current balance
{
cout << "Account Balance: $" << balance << endl;
return balance;
};
int main()
{
Account account(1500); // create an Account object named account with startingBal of $1500
account.credit(500);    // deposit $500 into account
account.withdraw(750);  // withdraw $750 from account
account.getBalance();   // display balance of account
system("PAUSE");    // to stop command prompt from closing automatically
return 0;
} // end main

balance成员变量永远不会分配给(在构造函数中),因此包含垃圾值。

事实上,你似乎有一个错误。在您的构造函数中,您设置了m_startingBal但不在其他任何地方使用它,而balance不是在构造函数中设置的,而是在其他任何地方使用