C++传递列表作为函数的参数

Adr*_*ian 13 c++ list pass-by-reference pass-by-value

我正在尝试构建一个非常简单的地址簿.我创建了一个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));
}
Run Code Online (Sandbox Code Playgroud)

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

ild*_*arn 12

您正在通过address_book值传递,因此会传递您传入的内容的副本,并且当您离开add_contact更改的范围时将丢失.

通过引用代替:

void add_contact(list<Contact>& address_book)
Run Code Online (Sandbox Code Playgroud)