1

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

//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 调用我的函数,我是否必须传递任何参数,如果没有,那么我如何访问函数 getMostExpensive() 内部的私有数据成员价格?

4

1 回答 1

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一个friendbook

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

在这种情况下L1,可以访问book.

然而,我的默认经验法则是,只要我需要friend's,我的设计就有缺陷: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

}
于 2012-11-08T16:58:05.147 回答