0

私はこの仕事を与えられましたが、情報が新しいデータに置き換えられるという問題にかなり悩まされています。新しい顧客が作成されると、新しい基本アカウントを作成する必要があります。これは問題なく機能しますが、それぞれ独自の値を含む学生/現在などの独自のルールを持つ複数のタイプのアカウントを持つ顧客を許可しようとしているためです。

何らかの理由で、アカウントの Money 値が現在設定されている値になり、何らかの理由で、異なる顧客の各アカウントでも内部の値が共有されます。したがって、account1 が £200 の場合、account2 は £300 で作成されます。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);

顧客.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 に答える