2.定义了Money类请补充完代码 #include <iostream> using namespace std; class Money { int Yuan, Jiao; // 元、角 public: Money(int y = 0, int j = 0) Money(double d) Money operator++(); //①用成员函数实现前置++ Money operator++(int); //②用成员函数实现后置++ friend Money operator--(Money &m); //③用友元函数实现前置-- friend Money operator--(Money &m, int); //④用友元函数实现后置-- operator double(); friend ostream & operator<<(ostream & out,Money & m); int main(void) { Money m(15, 3), m1, m2, m3, m4; cout<<"m:"<<m;//m.Show("m"); m1 = ++m; cout << "m1=++m;\n"<<"m1:"<<m1<<"m:"<<m; m2 = m++; cout << "m2=m++;\n"<<"m2:"<<m2<<"m:"<<m; m3 = --m; cout << "m3=--m;\n"<<"m3:"<<m3<<"m:"<<m; m4 = m--; cout << "m4=m--;\n"<<"m4:"<<m4<<"m:"<<m; Money m5 = m4 + 8.5; //A行 cout<<"m5= m4 + 8.5\nm5:"<<m5; return 0; }
时间: 2024-03-15 11:45:36 浏览: 141
下面是补充完整的Money类代码:
```c++
#include <iostream>
using namespace std;
class Money {
int Yuan, Jiao; // 元、角
public:
Money(int y = 0, int j = 0) : Yuan(y), Jiao(j) {}
Money(double d) {
Yuan = static_cast<int>(d);
Jiao = static_cast<int>((d - Yuan) * 10 + 0.5);
}
Money operator++(); //①用成员函数实现前置++
Money operator++(int); //②用成员函数实现后置++
friend Money operator--(Money &m); //③用友元函数实现前置--
friend Money operator--(Money &m, int);//④用友元函数实现后置--
operator double() { return Yuan + Jiao / 10.0; }
friend ostream & operator<<(ostream & out,Money & m);
Money operator+(double x) {
Money temp(*this);
temp.Yuan += static_cast<int>(x);
temp.Jiao += static_cast<int>((x - static_cast<int>(x)) * 10 + 0.5);
return temp;
}
};
Money Money::operator++() {
Jiao++;
if(Jiao == 10) {
Jiao = 0;
Yuan++;
}
return *this;
}
Money Money::operator++(int) {
Money temp(*this);
Jiao++;
if(Jiao == 10) {
Jiao = 0;
Yuan++;
}
return temp;
}
Money operator--(Money &m) {
m.Jiao--;
if(m.Jiao == -1) {
m.Jiao = 9;
m.Yuan--;
}
return m;
}
Money operator--(Money &m, int) {
Money temp(m);
m.Jiao--;
if(m.Jiao == -1) {
m.Jiao = 9;
m.Yuan--;
}
return temp;
}
ostream & operator<<(ostream & out, Money & m) {
out << m.Yuan << "." << m.Jiao << "元";
return out;
}
int main(void) {
Money m(15, 3), m1, m2, m3, m4;
cout << "m:" << m << endl;
m1 = ++m;
cout << "m1=++m;\n" << "m1:" << m1 << "m:" << m << endl;
m2 = m++;
cout << "m2=m++;\n" << "m2:" << m2 << "m:" << m << endl;
m3 = --m;
cout << "m3=--m;\n" << "m3:" << m3 << "m:" << m << endl;
m4 = m--;
cout << "m4=m--;\n" << "m4:" << m4 << "m:" << m << endl;
Money m5 = m4 + 8.5; //A行
cout << "m5= m4 + 8.5\nm5:" << m5 << endl;
return 0;
}
```
Money类中的主要成员函数和友元函数功能如下:
- Money(int y = 0, int j = 0):构造函数,初始化元和角;
- Money(double d):构造函数,根据浮点数d初始化元和角;
- Money operator++():前置++,使元和角都加1;
- Money operator++(int):后置++,使元和角都加1,但返回原对象的副本;
- friend Money operator--(Money &m):前置--,使元和角都减1;
- friend Money operator--(Money &m, int):后置--,使元和角都减1,但返回原对象的副本;
- operator double():类型转换运算符,将对象转换为浮点数;
- friend ostream & operator<<(ostream & out,Money & m):输出运算符,输出对象的元和角;
- Money operator+(double x):重载+运算符,将Money对象和浮点数相加,返回结果Money对象。
在main函数中,先创建一个Money对象m(15, 3),然后依次调用前置++、后置++、前置--、后置--和重载+运算符,最后将结果输出。
阅读全文