使用set函数的C ++ Update Object属性

时间:2015-10-02 14:45:06

标签: c++ function class object set

我正在写一个书店计划。该程序在矢量中存储了许多书籍及其相关值(标题,价格,isbn,作者)。我尝试编写的功能之一是通过isbn搜索向量并更新任何书籍匹配的值。这是我的代码

void UpdateOnIsbn(vector <CBooks> booklist)
{
    string searchisbn;
    char response;
    string booktitle;
    string author;
    double price;
    string ISBN;

    cout << "Please enter an ISBN to be searched: ";
    cin >> searchisbn;

    for (int i = 0; i < booklist.size(); i++)
    {
        if (booklist[i].HasISBN(searchisbn))
        {
            booklist[i].Display();

            cout << "Would you like to update the details of this book? (Y/N): ";
            cin >> response;

            if (response != 'n' && response != 'N')
            {


                    cout << endl << "Please Enter New Title for book: ";
                    cin >> booktitle;
                    booklist[i].SetTitle(booktitle);

                    cout << endl << "Please Enter New Author ";
                    cin >> author;
                    booklist[i].SetAuthor(author);

                    cout << endl << "Please Enter New Price ";
                    cin >> price;
                    booklist[i].SetPrice(price);

                    cout << endl << "Please Enter New ISBN ";
                    cin >> ISBN;
                    booklist[i].SetISBN(ISBN);





            } 

        }
    }
}

该功能似乎可以正常工作,因为它会查找要输入的新值,但在运行后,当我再次显示书籍时,旧值不会被替换。请帮忙

以下是其中一个设定函数的示例:

void CBooks::SetPrice(double NewPrice)
{
    m_Price = NewPrice;
} 

2 个答案:

答案 0 :(得分:1)

您正在传递booklist的副本,因此您正在修改副本而不是原始对象。

尝试传递对函数void UpdateOnIsbn(vector <CBooks>& booklist)

的引用

答案 1 :(得分:0)

您需要通过引用传递booklist

void UpdateOnIsbn(vector <CBooks>& booklist)

否则复制矢量并仅修改此副本。