指针覆盖旧指针

时间:2012-11-25 21:36:45

标签: c++ pointers

我已经接受了这项任务,并且在被新数据替换的信息方面遇到了很多麻烦。创建新客户时,他们必须创建一个新的基本帐户。这样可以正常工作,但我正在尝试允许具有多种类型帐户的客户各自拥有自己的规则,例如student / current,每个规则都包含自己的值。

由于某种原因,我的帐户的Money值变为当前设置的任何值,并且由于某种原因,即使是不同的客户,每个帐户也分享内部的价值。因此,如果account1有200英镑,那么然后用300英镑创建account2。 account1将设置为300英镑。

Customer.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);

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;
}

1 个答案:

答案 0 :(得分:2)

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

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

(为什么Customer无论如何通过引用存储帐户?)