将struct成员传递给函数C ++

时间:2012-10-16 08:50:12

标签: 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++;
}

2 个答案:

答案 0 :(得分:6)

你在没有参数的情况下调用addAmount();。你可能意味着

addAmount(books[i], 42);

另请考虑将printBooks签名更改为

void printBook(const Book& b)

或者更好的是,使其成为会员功能。

答案 1 :(得分:1)

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;
}