2、运算符重载(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 19:15:16 浏览: 106
C/C++ 学习入门代码案例 - class类的构造、运算符、继承、重载、多态等实例
以下是类 `Product` 的完整定义及四个函数的实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
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::Product(string n, int p, int q) {
name = n;
price = p;
quantity = q;
}
Product Product::operator=(const Product& p) {
name = p.name;
price = p.price;
quantity = p.quantity;
return *this;
}
bool operator>(const Product& p1, const Product& p2) {
if (p1.price > p2.price) {
return true;
} else {
return false;
}
}
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("Product1", 10, 50);
Product p2("Product2", 20, 30);
cout << "p1: " << endl;
cout << p1 << endl;
cout << "p2: " << endl;
cout << p2 << endl;
if (p1 > p2) {
cout << "p1 is more expensive than p2." << endl;
} else {
cout << "p2 is more expensive than p1." << endl;
}
p2 = p1;
cout << "p2 after assignment: " << endl;
cout << p2 << endl;
return 0;
}
```
输出结果为:
```
p1:
Product Name: Product1
Price: 10
Quantity: 50
p2:
Product Name: Product2
Price: 20
Quantity: 30
p2 is more expensive than p1.
p2 after assignment:
Product Name: Product1
Price: 10
Quantity: 50
```
其中,运算符重载函数 `operator>` 用于比较两个产品的单价大小,运算符重载函数 `operator<<` 用于输出产品的信息,运算符重载函数 `operator=` 用于实现产品对象之间的赋值操作。在主函数中,我们创建了两个产品对象 `p1` 和 `p2`,并对它们进行了比较和赋值操作。
阅读全文