C++ 使用 set 函数更新对象属性
C++ Update Object attributes using set function
我正在编写一个书店程序。该程序将许多书籍及其相关值(书名、价格、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;
}
您正在传递 booklist
的副本,因此您修改的是副本而不是原始对象。
尝试传递对函数的引用 void UpdateOnIsbn(vector <CBooks>& booklist)
您需要通过引用传递booklist
:
void UpdateOnIsbn(vector <CBooks>& booklist)
否则向量被复制,只有这个副本被修改。
我正在编写一个书店程序。该程序将许多书籍及其相关值(书名、价格、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;
}
您正在传递 booklist
的副本,因此您修改的是副本而不是原始对象。
尝试传递对函数的引用 void UpdateOnIsbn(vector <CBooks>& booklist)
您需要通过引用传递booklist
:
void UpdateOnIsbn(vector <CBooks>& booklist)
否则向量被复制,只有这个副本被修改。