我剛剛開始學習如何編碼,但遇到了一個我似乎無法解決的問題。更具體地說,問題發生在“借用”功能中。
在下面的程式中,即使我使用了 getter 和 setter,我也無法更新公共類變數“stock”的值。它似乎在 cout 之后正確更新,但沒有“永久保存”。我的猜測是它正在修改變數的副本而不是變數本身。
我已將我的代碼附加到帖子中!如果我應該上傳整個檔案,請告訴我!
提前致謝!
void Book::borrows() {
int searchid;
bool isfound=false;
cout<<"Please enter the unique ID of the book:\t\t";
cin>>searchid;
for(auto i:myBooks){
if (i.id==searchid){
cout<<"This book matches your search:\t"; print(i);
if (i.stock==0) {
cout<<"Book is out of stock!"<<endl;
} else {
setStock((i.stock-1));
cout<<"Successfully borrowed!! Now there are only "<<getStock()<<" copies left in stock!"<<endl;
}
isfound=true;
}
}
if (isfound== false){
cout<<" \t\tBook not found \t\t"<<endl;
}
system("pause");
}
int Book::getStock() const {
return stock;
}
void Book::setStock(int newstock) {
Book::stock = newstock;
}
編輯1:
這是我的類結構和向量:
class Book{
public:
int id;
string title;
int stock;
void add();
void displayall();
void displayspecific();
void print(Book);
void borrows();
void returns();
int getStock() const;
void setStock(int stock);
};
vector<Book> myBooks;
uj5u.com熱心網友回復:
您的實際問題是您正在操作 Book 物件的副本,而不是 book 成員的 setter 和 getter。
for(auto i:myBooks){
你需要
for(auto &i:myBooks){
但正如其他人指出的那樣,您需要 2 個類,圖書館和書。
uj5u.com熱心網友回復:
我同意托馬斯馬修斯的評論。您當前的Book結構沒有意義,因為大多數方法都是用于處理Books 的集合而不是特定的Book
如果您將書籍集合稱為 aLibrary那么下面的代碼對于委派作業在哪里完成Book和Library
#include <string>
#include <vector>
using namespace std;
class Book {
public:
int id;
string title;
int stock;
// These methods operate on this particular Book instance
int getStock() const;
void setStock(int);
};
int Book::getStock() const {
return stock;
}
void Book::setStock(int newstock) {
stock = newstock;
}
class Library {
public:
vector<Book> myBooks;
// These methods operate on the vector of books
void add();
void displayall();
void displayspecific();
//void print(Book); // This method probably belongs inside Book
void borrows();
void returns();
};
int main() {
return 0;
}
borrows用方法重寫Library意味著對那個Library向量myBooks進行操作。當您Book在向量中找到您想要的特定內容時,您可以呼叫它的 getter 和 setter,它們應該可以正常作業
解決您的問題,在您當前的代碼中,這是迭代您Book的 s 并為您提供每個副本:
for(auto i:myBooks)
您希望它獲得參考而不是副本:
for(auto& i:myBooks)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/460299.html
上一篇:為什么將方法分配給C#中的變數?
