【发布时间】:2012-03-07 08:11:37
【问题描述】:
我正在尝试构建一个非常简单的通讯录。我创建了一个 Contact 类,地址簿是一个简单的列表。我正在尝试构建一个功能以允许用户将联系人添加到地址簿。如果我将我的代码放在函数之外,它可以正常工作。但是,如果我把它放进去,它就不起作用了。我相信这是一个通过引用传递与通过值传递的问题,我没有按我应该的方式对待。这是函数的代码:
void add_contact(list<Contact> address_book)
{
//the local variables to be used to create a new Contact
string first_name, last_name, tel;
cout << "Enter the first name of your contact and press enter: ";
cin >> first_name;
cout << "Enter the last name of your contact and press enter: ";
cin >> last_name;
cout << "Enter the telephone number of your contact and press enter: ";
cin >> tel;
address_book.push_back(Contact(first_name, last_name, tel));
}
我没有收到任何错误,但是当我尝试显示所有联系人时,我只能看到原始联系人。
【问题讨论】:
-
调用
add_contact(addressBook);时list<Contact> addressBook没有更新
标签: c++ list pass-by-reference pass-by-value