简体   繁体   English

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

[英]Passing a struct member to function C++

Ok,so I have a struct and I need to create a function that increases the amount of a book.After calling the function for each book ,I will call printBooks which I can do just fine.I know it's a very simple program but I just couldn't do it so any help is appreciated 好的,所以我有一个结构,我需要创建一个增加书本数量的函数。为每本书调用该函数后,我将调用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++;
}

You're calling addAmount(); 您正在调用addAmount(); without parameters. 没有参数。 You probably mean 你可能是说

addAmount(books[i], 42);

Also consider changing the printBooks signature to 还可以考虑将printBooks签名更改为

void printBook(const Book& b)

or, even better, making it a member function. 或者,甚至使其成为成员函数。

void addAmount(Book &book)
{
    book.amount++;
}

and then 接着

addAmount(books[i]);

Btw, you don't really need to pass a structure by value to printBooks . 顺便说一句,您实际上并不需要按值将结构传递给printBooks Just use a const reference instead. 只需使用const引用即可。 The calling code doesn't need to be modified. 调用代码不需要修改。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM