【问题标题】:Passing a struct member to function C++将结构成员传递给函数 C++
【发布时间】:2012-10-06 07:49:03
【问题描述】:

好的,所以我有一个结构,我需要创建一个增加一本书的数量的函数。在为每本书调用该函数后,我将调用 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++;
}

【问题讨论】:

    标签: c++ struct pass-by-reference


    【解决方案1】:

    您正在调用addAmount(); 没有参数。你可能是说

    addAmount(books[i], 42);
    

    还可以考虑将printBooks 签名更改为

    void printBook(const Book& b)
    

    或者,甚至更好,使其成为成员函数。

    【讨论】:

    • 并将 book.amount++; 更改为 book.amount += amount; 以便使用参数,而不是仅添加一个。
    【解决方案2】:
    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      相关资源
      最近更新 更多