比较水果单价的大小,并输出赋值运算符的重载
时间: 2023-07-13 10:27:26 浏览: 45
可以定义一个`Fruit`类来表示水果,其中包含水果的名称和单价两个成员变量,同时可以重载小于运算符`<`来比较水果单价的大小。重载赋值运算符`=`可以用于将一个`Fruit`对象的值赋给另一个`Fruit`对象。
示例代码如下:
```cpp
#include <iostream>
#include <string>
class Fruit {
public:
Fruit() {}
Fruit(const std::string& name, double price) : name_(name), price_(price) {}
Fruit(const Fruit& other) : name_(other.name_), price_(other.price_) {}
bool operator<(const Fruit& other) const {
return price_ < other.price_;
}
Fruit& operator=(const Fruit& other) {
if (this != &other) {
name_ = other.name_;
price_ = other.price_;
}
return *this;
}
std::string getName() const {
return name_;
}
double getPrice() const {
return price_;
}
private:
std::string name_;
double price_;
};
int main() {
Fruit apple("apple", 3.0);
Fruit banana("banana", 2.5);
if (apple < banana) {
std::cout << "The price of " << apple.getName() << " is lower than that of " << banana.getName() << std::endl;
} else {
std::cout << "The price of " << apple.getName() << " is higher than that of " << banana.getName() << std::endl;
}
Fruit orange("orange", 2.0);
apple = orange;
std::cout << "After assignment: " << apple.getName() << " " << apple.getPrice() << std::endl;
return 0;
}
```
输出结果:
```
The price of apple is higher than that of banana
After assignment: orange 2
```
在上面的代码中,`Fruit`类中重载了`<`运算符和`=`运算符。在`main`函数中,我们创建了两个`Fruit`对象`apple`和`banana`,然后比较它们的单价,输出较低单价的水果名称。接着,我们创建了另一个`Fruit`对象`orange`,并将其赋值给`apple`,最后输出`apple`对象的名称和单价,可以看到赋值运算符重载成功。