运算符重载(60分) 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 08:32:38 浏览: 20
下面是代码实现:
```cpp
#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) {
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 << "Product: " << t.name << ", Price: " << t.price << ", Quantity: " << t.quantity << endl;
return out;
}
};
int main() {
Product p1("product1", 10, 100);
Product p2("product2", 20, 200);
// 输出商品信息
cout << p1 << p2;
// 比较商品价格
if (p1 > p2) {
cout << "p1 is more expensive than p2." << endl;
}
else {
cout << "p2 is more expensive than p1." << endl;
}
// 赋值运算符重载
p1 = p2;
cout << "After p1 = p2: " << endl;
cout << p1 << p2;
return 0;
}
```
输出结果如下:
```
Product: product1, Price: 10, Quantity: 100
Product: product2, Price: 20, Quantity: 200
p2 is more expensive than p1.
After p1 = p2:
Product: product2, Price: 20, Quantity: 200
Product: product2, Price: 20, Quantity: 200
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)