gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:12:59 24 4
gpt4 key购买 nike

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

//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() 内的私有(private)数据成员价格?

最佳答案

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

如果确实可以公开,为什么不使用更简单的 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的,我的设计有缺陷 :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

}

关于c++ - 如何将对象列表传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13293499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com