我创建了作为类Person
成员的类,Account
然后有Bank
一个包含vector
.Accounts
我创建了一个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;
}