设计一个Money类,包含有元、角、分,能够实现+(加法)、<<、>>三种运算符的重载运算。c++
时间: 2024-02-06 07:04:37 浏览: 136
好的,下面是一个简单的Money类的实现,包含元、角、分三个成员变量,以及重载了+、<<、>>三种运算符:
```cpp
#include <iostream>
class Money {
public:
Money(int yuan = 0, int jiao = 0, int fen = 0) : yuan_(yuan), jiao_(jiao), fen_(fen) {}
Money operator+(const Money& other) const {
int yuan = yuan_ + other.yuan_;
int jiao = jiao_ + other.jiao_;
int fen = fen_ + other.fen_;
if (fen >= 10) {
jiao += fen / 10;
fen = fen % 10;
}
if (jiao >= 10) {
yuan += jiao / 10;
jiao = jiao % 10;
}
return Money(yuan, jiao, fen);
}
friend std::ostream& operator<<(std::ostream& os, const Money& money) {
os << money.yuan_ << "元" << money.jiao_ << "角" << money.fen_ << "分";
return os;
}
friend std::istream& operator>>(std::istream& is, Money& money) {
char ch;
is >> money.yuan_ >> ch >> money.jiao_ >> ch >> money.fen_;
return is;
}
private:
int yuan_;
int jiao_;
int fen_;
};
```
在这个Money类中,重载了+运算符,可以对两个Money对象进行相加操作,返回一个新的Money对象,实现了元、角、分的进位。同时,重载了<<、>>运算符,可以方便地输出和输入Money对象。
下面是一个简单的测试代码:
```cpp
int main() {
Money a(10, 5, 8);
Money b(3, 6, 9);
Money c = a + b;
std::cout << c << std::endl;
Money d;
std::cin >> d;
std::cout << d << std::endl;
return 0;
}
```
输出结果为:
```
14元2角7分
12元3角4分
```
阅读全文