我正在尝试制作一个有两个帐户余额的程序,一个用于银行卡,另一个用于银行帐户。我已经为每个做了class
,但是当我尝试通过类指针调用转发卡class
中的借记方法时,我的程序崩溃了(它编译时没有错误)。
GoCardAccount.cpp 文件:
#include <cstdio>
#include "GoCardAccount.hpp"
#include "BankAccount.hpp"
GoCardAccount::GoCardAccount(long initialamount, BankAccount(ba)) {
balance = initialamount;
}
bool GoCardAccount::trip(long amount) {
LOW_LIMIT = 1000;
TOP_UP = 5000;
if(balance >= amount) {
balance -= amount;
if(balance < LOW_LIMIT) {
if(ba->debit(TOP_UP)) {
printf("Balance fallen below minimum, "
"topped up $50 to go card account.\n");
balance += TOP_UP;
return true;
}
else {
printf("Your balance has gone below minimum amount, however "
"there are insufficient funds in bank account to top up.\n");
return true;
}
}
}
else {
return false;
}
}
long GoCardAccount::getBalance() {
return balance;
}
GoCardAccount.hpp 档案:
class BankAccount;
class GoCardAccount {
long balance;
BankAccount *ba;
long LOW_LIMIT;
long TOP_UP;
public:
GoCardAccount(long amount, BankAccount(ba));
bool trip(long amount);
long getBalance();
};
来自 BankAccount.cpp 的借记方法:
bool BankAccount::debit(long amount1) {
if(amount1 >=0 && amount1 <= balance) {
balance -= amount1;
return true;
}
else {
return false;
}
}
我初始化类的main
函数的开头:
int main(void) {
long startamount;
long gocardamount;
printf("Input initial bank balance: \n");
scanf("%ld", &startamount);
BankAccount ba(startamount);
printf("Input initial Go-Card balance: \n");
scanf("%ld", &gocardamount);
GoCardAccount gca(gocardamount, ba);
}
答案 0 :(得分:0)
首先让我们来谈谈您class GoCardAccount
的构造函数,因为{em>有效STL (2001)中的Scott Meyers使用了一个术语, most vexing parse:
GoCardAccount(long amount, BankAccount(ba));
上面的代码片段将声明一个带有两个参数的构造函数:
long amount
参数名为amount
,其类型为long
。这很好。BankAccount(ba)
参数名为ba
,其类型为BankAccount
,因为ba
周围的括号是多余的,会被忽略。因此,上述声明与:
相同GoCardAccount(long amount, BankAccount ba);
这不是你想要的,因为第二个参数将按值BankAccount
实例,你需要一个指向它的指针。因此,您必须将其更改为:
GoCardAccount(long amount, BankAccount* ba);
更改其定义并按如下方式初始化您的BankAccount* ba
成员(或使用member initializer list):
GoCardAccount::GoCardAccount(long initialamount, BankAccount* ba_ptr) {
balance = initialamount;
ba = ba_ptr;
}
答案 1 :(得分:-1)
现在您正在尝试调用ba
方法,但BankAccount *ba;
甚至还没有实现。
您必须将BankAccount
上的指针传递给GoCardAccount
ctor。所以改变这一行(在主要部分)
GoCardAccount gca(gocardamount, ba);
到
GoCardAccount gca(gocardamount, &ba);
并在GoCardAccount
(GoCardAccount.cpp)中更改ctor
GoCardAccount::GoCardAccount(long initialamount, BankAccount(ba))
{
balance = initialamount;
}
到
GoCardAccount::GoCardAccount(long initialamount, BankAccount * pba) :
balance (initialamount), ba(pba) {}
论点
BankAccount(ba)
不会将传递给ctor的参数存储到ba
,这意味着函数调用中传递的参数将放在堆栈上,其标识符为ba
。
实施例
GoCardAccount::GoCardAccount(long initialamount, BankAccount * pba) : balance (initialamount), ba(pba) {}