水果店管理系统中要处理各种各样的水果,设计如下水果类(Fruit): class Fruit { public: Fruit(){}; double getPrice(){return m_price;}; friend istream& operator>>(istream &in, Fruit &f); friend ostream& operator<<(ostream &out, Fruit &f); private: int m_id{} ; //水果编号 string m_name{} ; //名称 double m_price{} ;//价格 }; 请完成友元函数的定义,在主函数中输入若干水果的信息,输出价格最贵的水果信息。 输入 第1行,一个整数n,表示水果的种类,以下n行,每行为一种水果的信息。 输出 最贵水果的信息。
时间: 2024-02-04 20:01:55 浏览: 42
好的,根据你的要求,我来给出解题思路和代码实现。
首先,根据题目要求,我们需要输入n个水果的信息,因此需要在Fruit类中定义输入运算符重载函数,用于输入水果的信息。在输入过程中,需要依次输入水果的编号、名称和价格。输入运算符重载函数的实现如下:
```
friend istream& operator>>(istream& in, Fruit& f) {
in >> f.m_id >> f.m_name >> f.m_price;
return in;
}
```
接着,我们需要输出价格最贵的水果的信息,因此需要遍历所有水果,找到价格最高的水果。在遍历过程中,需要记录最高价格和对应的水果编号、名称和价格。输出运算符重载函数的实现如下:
```
friend ostream& operator<<(ostream& out, Fruit& f) {
out << f.m_id << " " << f.m_name << " " << f.m_price;
return out;
}
```
最后,我们可以在主函数中输入n个水果的信息,找到价格最高的水果并输出其信息。实现代码如下:
```
#include <iostream>
#include <string>
using namespace std;
class Fruit {
public:
Fruit() {};
double getPrice() { return m_price; }
friend istream& operator>>(istream& in, Fruit& f);
friend ostream& operator<<(ostream& out, Fruit& f);
private:
int m_id{}; //水果编号
string m_name{}; //名称
double m_price{};//价格
};
istream& operator>>(istream& in, Fruit& f) {
in >> f.m_id >> f.m_name >> f.m_price;
return in;
}
ostream& operator<<(ostream& out, Fruit& f) {
out << f.m_id << " " << f.m_name << " " << f.m_price;
return out;
}
int main() {
int n;
cin >> n;
Fruit max_fruit;
double max_price = 0;
for (int i = 0; i < n; i++) {
Fruit f;
cin >> f;
if (f.getPrice() > max_price) {
max_price = f.getPrice();
max_fruit = f;
}
}
cout << max_fruit << endl;
return 0;
}
```
输入样例:
```
3
1 apple 3.5
2 banana 2.5
3 orange 4.5
```
输出样例:
```
3 orange 4.5
```
希望可以帮到你!
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)