C++ 将列表作为参数传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9302645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:37:47  来源:igfitidea点击:

C++ pass list as a parameter to a function

c++listpass-by-referencepass-by-value

提问by Adrian

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:

我正在尝试构建一个非常简单的地址簿。我创建了一个 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 don't get any errors however when I try to display all contacts, I can see only the original ones.

我没有收到任何错误,但是当我尝试显示所有联系人时,我只能看到原始联系人。

采纳答案by ildjarn

You're passing address_bookby value, so a copy of what you pass in is made and when you leave the scope of add_contactyour changes are lost.

您是address_book按值传递的,因此会复制您传入的内容,并且当您离开add_contact更改范围时会丢失。

Pass by reference instead:

改为通过引用传递:

void add_contact(list<Contact>& address_book)

回答by Krizz

Because you are passing list by value, thus it is copied, and new elements are added to a local copy inside add_contact.

因为您是按值传递列表,因此它被复制,并且新元素被添加到add_contact.

Solution: pass by reference

解决方案:通过引用传递

void add_contact(list<Contact>& address_book).

回答by Kerrek SB

Say void add_contact(list<Contact> & address_book)to pass the address book by reference.

void add_contact(list<Contact> & address_book)通过引用传递地址簿。

回答by Gran Torino

Pass by reference

通过引用传递

void add_contact(list<Contact>& address_book).