0 c++ struct pass-by-reference
好吧,所以我有一个结构,我需要创建一个增加书籍数量的函数.在为每本书调用函数后,我会调用printBooks,我可以做得很好.我知道这是一个非常简单的程序,但我只是不能这样做所以任何帮助表示赞赏
#include <iostream>
using namespace std;
#define BOOKS 3
struct Book
{
string title;
string isbn;
int amount;
} books [BOOKS];
void printBooks(Book b);
void addAmount(Book &book,int amount);
int main()
{
int i;
for(int i = 0;i < BOOKS; i++)
{
cout << "Enter isbn : ";
cin >> books[i].isbn;
cout << "Enter title : ";
cin >> books[i].title;
cout << "Enter amount : ";
cin >> books[i].amount;
}
cout << "\nThe number of books after adding amount by one :\n";
for(i = 0;i < BOOKS; i++)
{
addAmount(); // intentionally left blank.don't know what to put
printBooks(books[i]);
}
return 0;
}
void printBooks(Book b)
{
cout << b.isbn << endl;
cout << b.title << endl;
cout << b.amount << endl;
}
void addAmount(Book &book,int amount)
{
book.amount++;
}
Run Code Online (Sandbox Code Playgroud)
你addAmount();没有参数就打电话.你可能意味着
addAmount(books[i], 42);
Run Code Online (Sandbox Code Playgroud)
还要考虑将printBooks签名更改为
void printBook(const Book& b)
Run Code Online (Sandbox Code Playgroud)
或者,更好的是,使其成为会员功能.