class Product { string name; //产品名称 int price; //产品单价 int quantity; //剩余产品数量 public: Product(string n,int p int q); Product operator = (const Product &p); friend bool operator >(const Product &p1, const Product &p2); friend ostream& operator<<(ostream &out, Product &t ); }; 类Product说明如上所示,完成四个函数的定义,并在main函数中进行测试
时间: 2024-02-14 13:15:19 浏览: 93
Product.class
下面是类Product的函数定义:
```c++
#include <iostream>
using namespace std;
class Product {
string name; //产品名称
int price; //产品单价
int quantity; //剩余产品数量
public:
//构造函数
Product(string n, int p, int q) : name(n), price(p), quantity(q) {}
//赋值运算符重载
Product operator = (const Product &p) {
if (this == &p) {
return *this;
}
name = p.name;
price = p.price;
quantity = p.quantity;
return *this;
}
//比较运算符重载
friend bool operator > (const Product &p1, const Product &p2) {
return p1.price > p2.price;
}
//输出流运算符重载
friend ostream& operator << (ostream &out, Product &t) {
out << "名称:" << t.name << endl;
out << "单价:" << t.price << endl;
out << "剩余数量:" << t.quantity << endl;
return out;
}
};
int main() {
//测试
Product p1("苹果", 5, 10);
Product p2("香蕉", 3, 20);
Product p3("橘子", 4, 15);
//比较单价大小
cout << "p1 > p2 ? " << (p1 > p2) << endl;
cout << "p2 > p3 ? " << (p2 > p3) << endl;
cout << "p1 > p3 ? " << (p1 > p3) << endl;
//输出产品信息
cout << p1 << endl;
cout << p2 << endl;
cout << p3 << endl;
return 0;
}
```
输出结果如下:
```
p1 > p2 ? 1
p2 > p3 ? 0
p1 > p3 ? 1
名称:苹果
单价:5
剩余数量:10
名称:香蕉
单价:3
剩余数量:20
名称:橘子
单价:4
剩余数量:15
```
阅读全文