这是关于类(class)作业的介绍,我将在其中创建一个银行账户,该账户能够通过存款或取款来操纵余额并查询账户余额。
我查看了十几个不同的示例和操作方法,但现在我不知所措。
我从代码中得到的唯一输出是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
未在构造函数中设置但 在其他任何地方使用。
关于c++ - 介绍银行账户类 - 奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895710/