2012-11-25 89 views
0

我已經完成了這項任務,並且信息被新數據替換時遇到了相當多的麻煩。當新客戶被創建時,他們必須創建一個新的基本賬戶。這工作正常,但因爲我試圖讓客戶有多種類型的賬戶,每個賬戶都有自己的規則,比如學生/當前每個都包含自己的值。指針覆蓋舊的指針

由於某種原因,我的賬戶資金價值成爲目前設置的任何價值,並且由於某種原因,即使是不同客戶的每個賬戶也會分享價值。所以如果account1有200英鎊,那麼account2就是300英鎊。賬戶1將被設置爲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; 
} 
+0

注意,'的AccountManager accRef =賬戶;'不創建一個參考,你複製'account'對象。 – enobayram

+1

另外,嘗試提供一個演示您的問題的最小示例。所提供的代碼與所述問題無關。如果您提供一些簡單編譯和運行的代碼,您將得到相當快的答案。 – enobayram

回答

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

創建一個帳戶作爲局部變量,傳遞指向它的指針Customer構造函數,該指針,然後「一種方法」終止時,局部變量超出範圍時的Customer存儲,且Customer留下一個懸掛指針。然後你解除指針並得到奇怪的結果。

(爲什麼Customer商店賬戶通過參考呢?)