如何将对象列表传递给函数

时间:2012-11-08 16:39:51

标签: c++ arrays list

我正在编写一个函数,该函数应该接收一个book对象列表作为参数。在每个图书对象中都有一个私人数据成员价格。该功能假设比较每本书的价格并以最高价格退还书籍。

//Client program
#include <iostream>
#include "Book.h"
#include "textbook.h"
#include "Name.h"
#include "unsorted.h"
using namespace std;

int main()
{

book b1("The Exception to the Rulers", "Amy", "Goodman", "Hyperion", 342, "1-4013-0131", 21.95,'N'); // this is the title, authors first & last name, publisher, number of pages, isbn number, price, and code.
book b2("Who moved my cheese", "Spencer", "Johnson", "Red Tree", 95, "0-399-14446-3", 19.99,  'H');
book b3("Hellbound Hearts", "Neil", "Gaiman", "Dark Harvest", 326, "978-1-4391-4090-1", 16.00, 'F');

UnsortedType L1; // creating a list "L1" with the default vaule lengh 0

L1.InsertItem(b1); // populating the list with the first book
L1.InsertItem(b2); // populating the list with the second book
L1.InsertItem(b3); // populating the list with the third book

在主要我不确定如何将实际列表“L1”或L1的内容传递给将比较价格的功能。我想我很困惑,因为为了调用函数getMostExpensive我会做一些像:

L1.getMostExpensive();

但如果我用L1调用我的函数,我是否必须传递任何args,如果没有,那么如何访问函数getMostExpensive()中的私有数据成员价格?

1 个答案:

答案 0 :(得分:0)

为什么price应成为book的私人成员?在我看来,“每个人”应该能够知道一本书的价格...

如果您确实可以公开,为什么不使用更简单的std::vector<book>免费功能getMostExpensive()

#include <vector>

...

std::vector<book> L1; 

L1.push_back(b1); // include first book
L1.push_back(b2); // include second book
L1.push_back(b3); // include third book

...

// free function
book getMostExpensive(const std::vector<book>& b) {

    double maxPrice=0;
    unsigned int maxInd;
    for(unsigned int i=0; i<b.size(); ++i){
        if (b[i].price > maxPrice){
            maxInd = i;
            maxPrice = b[i].price;
        }
    }
    return b[maxInd];
}

如果您必须保留price private,则可以UnsortedType friend book {/ 1}}:

class UnsortedType;
class book {
    ...
    friend class UnsortedType;
    ...
};

在这种情况下,L1可以访问book的私有。

我的默认经验法则是,无论何时我需要friend,我的设计都存在缺陷:p

你也可以使用getter / setter方法:

class book 
{
private:
    double _price; // the actual price

public: 
    const double& price // read-only copy of price

    // constructor
    book(...);

    // price-setter
    void setPrice(double newPrice);

};

// constructor initializes const reference to private member _price
book::book(...) : price(_price) {...}

void book::setPrice(double newPrice) { _price = newPrice>=0.0?newPrice:0.0; }

...

int main(...){
    book b;
    ...
    double P = b.price;  // valid
    b.price = 56.8;      // NOT valid; compile-time error

    b.setPrice(56.8);    // valid; this is the only way to set the price

}
相关问题