C++将列表作为参数传递给函数
我正在尝试构建一个非常简单的地址簿。我创建了一个 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));
}
我没有收到任何错误,但是当我尝试显示所有联系人时,我只能看到原始联系人。
I'm trying to build a very simple address book. I created a Contact class and the address book is a simple list. I'm trying to build a function to allow the user to add contacts to the address book. If I take my code outside of the function, it works OK. However, if I put it in, it doesn't work. I believe it's a passing by reference vs passing by value problem which I'm not treating as I should. This is the code for the function:
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));
}
I don't get any errors however when I try to display all contacts, I can see only the original ones.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您按值传递
address_book
,因此会生成您传入的内容的副本,并且当您离开add_contact
范围时,您的更改将会丢失。通过引用传递:
You're passing
address_book
by value, so a copy of what you pass in is made and when you leave the scope ofadd_contact
your changes are lost.Pass by reference instead:
因为您是按值传递列表,所以它被复制,并且新元素被添加到
add_contact
内的本地副本中。解决方案:通过引用传递
Because you are passing list by value, thus it is copied, and new elements are added to a local copy inside
add_contact
.Solution: pass by reference
说
void add_contact(list& address_book)
通过引用传递地址簿。Say
void add_contact(list<Contact> & address_book)
to pass the address book by reference.通过引用传递
Pass by reference