我有一个BankAccount类,其数组由BankAccount对象组成。每个对象都有每个客户的名称,余额,银行帐户类型等。实现方式是通过BankAccount * customers [10]作为类私有字段的实现。然后,客户将使用所选构造函数填充对象。构成作为客户元素的每个对象的每条数据都由用户输入。在display()中输出数据,但问题是每个元素都会向客户重复最后一个输入对象。为什么这样重复?任何帮助或建议都会很棒!
BankAccount::BankAccount() : customers()
{
setAcctAmt();
}
void BankAccount::work()
{
for (int x = 0; x < accountAmount; x++)
{
bool t = true;
string theName, sT;
double balance, iRate;
cout << "Enter the name for account " << x + 1 << endl;
cin >> theName;
while (t)
{
if (t == false)
exit;
cout << "Bank Account type: Checking or Saving" << endl;
cin >> sT;
string s;
s = sT.substr(0, 1);
if (s == "c")
{
sT = "Checking Account ";
cout << "Input checking balance: ";
cin >> balance;
iRate = 0.02;
makeAcctNum();
constAcct(theName, balance, iRate, sT); // This is where customers is constructed and data is imput from parameters
t = false;
}
else if (s == "s")
{
sT = "Savings Account ";
cout << "Input saving balance: ";
cin >> balance;
iRate = 0.07;
makeAcctNum();
constAcct(theName, balance, iRate, sT); // The constructed object
t = false;
}
else
cout << "Error, enter checking or saving!" << endl;
}
}
display(); // This is the display function to display all constructed objects of customers
}
// This is the display function
void BankAccount::display()
{
for (int i = 0; i < accountAmount; i++)
{
cout << customers[i]->getAcctNum() << " " << customers[i]->getName() << " " << customers[i]->getType() << " " << customers[i]->getRate()
<< " " << customers[i]->getBalance();
}
}
// This is the constructor that will build each customers element as customer data
BankAccount::BankAccount(string* nam, int* acctNumber, double* balanc, double* rat, string* typ)
{
rate = rat;
account = acctNumber;
name = nam;
type = typ;
bal = balanc;
}
void BankAccount::deleteStuff()
{
delete name, type, bal, rate, account, customers;
}
// This constructs each customers element
void BankAccount::constAcct(string n, double ba, double r, string t)
{
nameS = n;
balD = ba;
rateD = r;
typeS = t;
name = &nameS;
account = &acctNumber;
rate = &rateD;
bal = &balD;
type = &typeS;
for (int i = 0; i < accountAmount; i++)
{
BankAccount* b = new BankAccount(name, account, bal, rate, type);
customers[i] = b;
}
}
答案 0 :(得分:1)
基于此评论和代码行:
// This is where customers is constructed and data is imput from parameters constAcct(theName, balance, iRate, sT);
您的意图似乎是使用constAcct
方法创建新帐户。
看看那个方法:
for (int i = 0; i < accountAmount; i++) { BankAccount* b = new BankAccount(name, account, bal, rate, type); customers[i] = b; }
您正在使用相同参数构建的customers
重写new BankAccount
数组中的所有条目(无论最后一个参数是什么)。
要解决此问题,您应该使用以下内容替换上述循环:
customers[lastAccountIndex++] = new BankAccount(name, account, bal, rate, type);
此处lastAccountIndex
是一个变量,用于跟踪已添加的帐户数量。