Account
클래스의 멤버 인 Person
클래스를 만들고 vector
이 Accounts
인 클래스 Bank
이 있습니다.하나의 개체에 대한 참조가 변경되어 컬렉션에서 모두 변경됨
Person
이 (가) 3 Accounts
을 소유하고 있습니다. changeOnwner()
하나의 계정으로 보내고 싶었지만 실수로 모든 계정에이 새로운 소유자가 있습니다. 코드가 실행 중이며 오히려 직관적입니다. 3 개의 계정 모두에서 참조가 변경된 이유를 모르겠습니다. 어떻게 해결할 수 있습니까?
#include <iostream>
#include <vector>
using namespace std;
class Person{
public:
char* name;
int age;
Person(char* name, int age){
this->name = name;
this->age = age;
}
~Person(){
}
void show(){
cout<<name<<" "<<age<<" yo";
}
};
class Account{
public:
Person& owner;
double money;
Account(Person* owner, double money):
owner(*owner) , // this->owner = *owner;
money(money) { //Uninitialized reference member
}
void show(){
cout<<"\n-------------\n";
owner.show();
cout<<endl;
cout<<money<<" USD\n-------------";
}
};
class Bank{
public:
vector<Account*>* v;
Bank(){
v = new vector<Account*>();
}
Account* openNewAccount(Person* client, double money){
Account* r = new Account(client, money);
v->push_back(r);
return r;
}
void zmienWlasciciela(Person& o, Account* r){
r->owner = o;
}
void usunRachunek(Account* r){
delete r;
}
void show(){
for(int i = 0; i < v->size(); i++)
v->at(i)->show();
}
~Bank(){
delete v;
}
};
int main(){
Bank* bank = new Bank();
Person* thomas = new Person("thomas", 34);
Account* r1 = bank->openNewAccount(thomas, 64363.32);
Account* r2 = bank->openNewAccount(thomas, 41251.54);
Account* r3 = bank->openNewAccount(thomas, 3232.32);
bank->show();
Person* margaret = new Person("Margaret", 23);
bank->zmienWlasciciela(*margaret, r2);
cout<<"I have changed owner of account r2"<<endl;
bank->show();
return 0;
}
규칙 3/5를 따라야합니다. –