2
我在地圖中插入了字符串和Person對象。但是,在我的方法中,當我嘗試在Person類中添加某些內容或在地圖中更改其成員數據時,我無法再訪問它。這是因爲當我使用迭代器並通過打印 i-> second來測試它時,我指向的Person類具有BLANK信息。這些Person對象的所有信息都被刪除(或者我認爲)。 我不明白爲什麼。 我的目標是打印地圖中Person對象的列表(成員數據)。當我遇到這個問題時我無法做到,因爲它會打印出空白。C++如何訪問和更改地圖中對象的成員數據?
下面是插入地圖中的字符串和Person對象方法的代碼:
void SocialNetwork::createPerson(string firstName, string lastName)
{
string fullName = firstName + " " + lastName;
//checks if the name is NOT A DUPLICATE
//iterate through _userList. _userList is a map
//if map is empty
if (_userList.empty())
{
_user = new Person(firstName, lastName);
_userList.insert(make_pair(fullName, *_user));
_numUsers++;
}
else
{
bool matchFound = false;
//USE MAP COUNT TO SEE IF THE PERSON ALREADY EXISTS IN THE MAP
if(_userList.count(fullName)>0)
{
matchFound = true;
cout << "Error: Name already exists" << endl;
}
else
{
_user = new Person(firstName, lastName);
_userList.insert(make_pair(fullName, *_user));
_numUsers++;
}
}
}
下面是一個方法的示例代碼,試圖在以下的人類打印出的列表:
void SocialNetwork::listPending(string personsFirst, string personsLast)
{
//prints list of pending Friend Requests
string personsFullName = personsFirst + " " + personsLast;
//check if this user exists
bool userExists = false;
if (_userList.empty())
{
cout << "Error: Person does not exist" << endl;
}
else
{
if(_userList.count(personsFullName)>0)
{
userExists = true;
}
if (!userExists)
{
cout << "Error: Person does not exist" << endl;
}
else
{
map<string,Person>::iterator i = _userList.begin();
bool personFound = false;
while (!personFound)
{
if(i != _userList.end())
{
if(i->first == personsFullName)
{
//PROBLEM IS HERE
personFound = true;
cout << i->second <<endl; //Test Code. Delete later. How come their Person class is left BLANK?
i->second.printPendingRequestList(); //How come the list is left BLANK?
}
i++;
}
}
}
}
}
這裏是在Person類printPendingRequestList方法:
void Person::printPendingRequestList()
{
string test = _fullName;
cout << _fullName << "'s pending list" << endl;
queue<Person> toPrintQueue = _friendRequests;
while (!toPrintQueue.empty())
{
cout << toPrintQueue.front().getFullName() << endl;
toPrintQueue.pop();
}
cout << endl;
}
這是我收到它應該有這個人的名字輸出,姓氏,和所有其他的信息,但不,這是留給默認或空白:
First Name:
Last Name:
Full Name:
Number of Friends: 0
Number of people they blocked: 0
Friend Requests:
Friend List:
Block List:
Personal Message List:
's pending list
請幫
在調用insert()後,映射的內容是否正確?另外,由於在將它傳遞給'make_pair()'時,您將取消引用Person *,因此將調用「Person」的複製構造函數。 'Person'使用默認的拷貝構造函數嗎?如果沒有,你是否證實它能正常工作? – Andy
這是一個印象,還是你有內存泄漏? – Christophe
爲什麼使用'new'在堆上分配'_user'? –