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

标签 c++ class

这是关于类(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/

相关文章:

html - Bootstrap "Buttons addons"不工作

c++ - 在 C++ 中创建一个文件,就像按右键->新建->新建文本文档一样

java - JVMT 异常监视器

c++ - GDB/DDD : Debug shared library with multi-process application C/C++

c++ - 合并共享一个共同元素的对

java - 如何创建一个类的实例,并将字符串数组作为唯一的实例变量?

c++ - 如何使用动态 unicode 文本设置 Win32 工具提示控件?

java - 创建一个狗类和测试器

java - 我们可以使用反射来获取类的静态成员而不在对象实例上调用该方法吗?

javascript - SVG - getElementsByClassName