0

我被赋予了这项任务,并且在将信息替换为新数据时遇到了很多麻烦。创建新客户时,他们必须创建一个新的基本帐户。这很好用,但是因为我试图让客户拥有多种类型的账户,每个账户都有自己的规则,例如学生/当前,每个账户都包含自己的值。

出于某种原因,我的账户的货币价值变成了当前设置的任何价值,并且出于某种原因,每个账户甚至对于不同的客户都共享里面的价值。因此,如果 account1 有 200 英镑,那么 account2 就会用 300 英镑创建。然后将 account1 设置为 300 英镑。

客户.h

Customer(std::string sFirstName, std::string sLastName, 
    std::string sAddressLnA,
    std::string sAddressLnB,
    std::string sCity,
    std::string sCounty,
    std::string sPostcode,
    AccountManager* bankAccount);

    AccountManager* getAccount(void);

    //outside class
    std::ostream& operator << (std::ostream& output, Customer& customer);

客户.cpp

//Part of a method but i've shrunk it down
AccountManager account(H);
AccountManager accRef = account; //This the issue?
Customer c(A, B, C, D, E, F, G, &accRef);
customerList.insert(c);
showPersonDetails();

//Output
ostream& operator << (ostream& output, Customer& customer)
{
    output << customer.getFirstName() << " " << customer.getLastName() << endl
        << customer.getaddressLnA() << endl
        << customer.getaddressLnB() << endl
        << customer.getcity() << endl
        << customer.getcounty() << endl
        << customer.getpostcode() << endl
        << (*customer.getAccount()) << endl;
    return output;

AccountManager.h

class AccountManager
{
private:
    double money;
public:
    AccountManager(double amount);
    ~AccountManager(void);
    double getMoney();

};

//Print
std::ostream& operator << (std::ostream& output, AccountManager& accountManager);

AccountManager.cpp

using namespace std;

AccountManager::AccountManager(double amount)
{
    money = amount;
}

AccountManager::~AccountManager()
{
}

double AccountManager::getMoney()
{
    return money;
}

ostream& operator << (ostream& output, AccountManager& accountManager)
{
    //Type of account
    output << "Account Money: " << accountManager.getMoney() << endl;
    return output;
}
4

1 回答 1

2
AccountManager accRef = account; //This the issue?
Customer c(A, B, C, D, E, F, G, &accRef);

您创建一个帐户作为局部变量,将指向它的指针传递给Customer构造函数,Customer存储该指针,然后“方法”终止,局部变量超出范围,Customer留下一个悬空指针。然后你取消引用指针并得到奇怪的结果。

(为什么Customer仍然通过引用存储帐户?)

于 2012-11-25T22:34:45.890 回答