指针覆盖旧指针

Pointers overriding older pointers

本文关键字:指针 覆盖      更新时间:2023-10-16

我接到了这个任务,并且在信息被新数据替换时遇到了很多麻烦。创建新客户时,他们必须创建一个新的基本帐户。这工作正常,但我试图允许拥有多种类型的帐户的客户,每个帐户都有自己的规则,例如学生/当前,每个帐户都包含自己的值。

由于某种原因,

我的帐户的货币价值成为当前设置的任何值,并且由于某种原因,每个帐户甚至针对不同的客户共享其中的价值。因此,如果帐户 1 有 200 英镑,那么帐户 2 则创建 300 英镑。然后,帐户 1 将设置为 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;

客户经理.h

class AccountManager
{
private:
    double money;
public:
    AccountManager(double amount);
    ~AccountManager(void);
    double getMoney();
};
//Print
std::ostream& operator << (std::ostream& output, 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;
}
AccountManager accRef = account; //This the issue?
Customer c(A, B, C, D, E, F, G, &accRef);

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

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