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 20:15:13 浏览: 71
Product.class
根据题意,以下是类Product的完整代码,包括构造函数、赋值运算符重载、大于运算符重载和流插入运算符重载:
```c++
#include <iostream>
#include <string>
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 Name: " << t.name << endl;
out << "Price: " << t.price << endl;
out << "Quantity: " << t.quantity << endl;
return out;
}
};
int main() {
Product p1("Product A", 10, 20);
Product p2("Product B", 5, 30);
// 测试赋值运算符重载
p2 = p1;
cout << "After assign p1 to p2:\n" << p2 << endl;
// 测试大于运算符重载
if (p1 > p2) {
cout << "p1 is more expensive than p2.\n";
} else {
cout << "p2 is more expensive than p1.\n";
}
// 测试流插入运算符重载
cout << "Product Info:\n" << p1 << endl;
return 0;
}
```
在main函数中,我们定义了两个Product对象p1和p2,并测试了赋值运算符重载、大于运算符重载和流插入运算符重载的正确性。
阅读全文