[英]C / C++ : passing a struct / class with a member array to a function by value
[英]Passing a struct member to function C++
好的,所以我有一個結構,我需要創建一個增加書本數量的函數。為每本書調用該函數后,我將調用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++;
}
您正在調用addAmount();
沒有參數。 你可能是說
addAmount(books[i], 42);
還可以考慮將printBooks
簽名更改為
void printBook(const Book& b)
或者,甚至使其成為成員函數。
void addAmount(Book &book)
{
book.amount++;
}
接着
addAmount(books[i]);
順便說一句,您實際上並不需要按值將結構傳遞給printBooks
。 只需使用const引用即可。 調用代碼不需要修改。
void printBooks(const Book &b)
{
cout << b.isbn << endl;
cout << b.title << endl;
cout << b.amount << endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.