我一直致力于一项微不足道的工作,习惯于编码。我正在设计一台ATM机,目前它由两个类组成:
BankAccount.cpp
Transaction.cpp
问题: BankAccount会自动初始化为10的余额,这是不受欢迎的。例如,如果我创建一个支票账户并选择存入10美元,那么余额将打印出20美元。
//BankAccount.h
//This class will simply take in a bank account
//with a balance, other classes will use a bank account object
//such as saving/checkings and perform operations on the
//balance
#ifndef BANK_ACCOUNT_H
#define BANK_ACCOUNT_H
class BankAccount {
private:
float balance;
public:
BankAccount ();
float getBalance ();
void makeDeposit ();
void makeWithdrawl ();
};
#endif
//BankAccount.cpp
#include "BankAccount.h"
#include <iostream> //remove once done *not to self
using namespace std; //remove once done *note to self
BankAccount::BankAccount() {
balance = 0.00;
}
float BankAccount::getBalance() {
return balance;
}
void BankAccount::makeDeposit() {
cout << "How much would you like to deposit: ";
float deposit_value;
cin >> deposit_value;
balance += deposit_value;
}
void BankAccount::makeWithdrawl() {
cout << "How much would you like to withdrawl: ";
float withdrawl_value;
cin >> withdrawl_value;
balance -= withdrawl_value;
}
//Transaction.h
#ifndef TRANSACTION_H
#define TRANSACTION_H
class Transaction {
private:
BankAccount m_bao;
public:
Transaction(BankAccount&);
void displayOptions();
void printReciept();
};
#endif
//Transaction.cpp
#include "BankAccount.h"
#include "Transaction.h"
#include <iostream>
using namespace std;
Transaction::Transaction(BankAccount& bao) {
m_bao = bao;
}
void Transaction::displayOptions() {
cout << "\nPlease make a choice\n\n";
cout << "1: Make Deposit\n";
cout << "2: Make Withdrawl\n";
cout << "3: Check Balance\n";
int choice;
cin >> choice;
switch (choice) {
case 1:
m_bao.makeDeposit();
break;
case 2:
m_bao.makeWithdrawl();
break;
case 3:
m_bao.getBalance();
break;
}
}
void Transaction::printReciept() {
cout << "Current balance is now: " << m_bao.getBalance() + '\n';
}
int main () {
BankAccount checking;
Transaction q(checking);
q.displayOptions();
q.printReciept();
}
我确信答案就在眼前,但我的大脑现在才被炸好。我会继续寻找解决方案,让你们知道我的问题是否已经解决了。
[编辑]
好吧,现在我正在努力使客户可以选择在支票或储蓄账户上执行交易。目前我在main()中看起来像这样:
int main () {
BankAccount checking(0.00);
BankAccount savings(0.00);
Transaction c(checking);
Transaction s(savings);
for(int i = 0; i < 10 ; i++) {
cout << "Make an option" << endl;
cout << "1. Checking " << endl;
cout << "2. Savings" << endl;
int choice;
cin >> choice;
if (choice == 1) {
c.prompt();
c.printReciept();
}
else {
s.prompt();
s.printReciept();
}
}
}
它工作正常,但如果有意义的话,我想让这个过程更加OOP-alized :)
我试图研究的一个选项是创建一个属于Transaction.cpp的提示函数。除了初始化对象之外,这将完成在main中完成的所有操作。
答案 0 :(得分:5)
你的问题就在这一行:
cout << "Current balance is now: " << m_bao.getBalance() + '\n';
编译器认为:
cout << "Current balance is now: " << (m_bao.getBalance() + '\n');
'\n'
是10
作为int,所以你得到了这个:
cout << "Current balance is now: " << (m_bao.getBalance() + 10);
您可能打算这样做:
cout << "Current balance is now: " << m_bao.getBalance() << '\n';
请记住,在C ++中,+
几乎总是意味着“添加这两个数字”。