C ++传递列表作为函数的参数 [英] C++ pass list as a parameter to a function

查看:262
本文介绍了C ++传递列表作为函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个非常简单的通讯簿.我创建了一个Contact类,通讯录是一个简单的列表.我正在尝试构建一个允许用户将联系人添加到通讯簿的功能.如果我将代码放在函数之外,则可以正常工作.但是,如果我放进去,那是行不通的.我认为这是一个参考传递与价值传递的问题,我没有认真对待.这是该函数的代码:

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.

推荐答案

您正在按值传递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 of add_contact your changes are lost.

通过参考传递:

void add_contact(list<Contact>& address_book)

这篇关于C ++传递列表作为函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆