📄 eam0-4.cpp
字号:
#include <iostream.h>
#include <stdlib.h>
enum sign{minus, plus}; //正负数的符号标识
//类Money定义部分
class Money //类Money定义
{
private: //私有部分
friend ostream& operator<<(ostream& out, const Money& x);
//运算符<<重载,设计成类的友元
long amount; //类Money的属性,以分为单位
public: //公有部分
//构造函数
Money(sign s = plus, unsigned long d = 0, unsigned long c = 0);
~Money(){}; //析构函数
bool Set(sign s, unsigned long d, unsigned long c); //设置成员函数
Money operator+(const Money& x) const; //加运算符
Money& operator+=(const Money& x) //加等于运算符
{amount += x.amount; return *this;}//this是默认的当前对象指针
};
//类Money实现部分
Money::Money(sign s, unsigned long d, unsigned long c)
//构造函数。s为符号, d为元值,c为分值
{
if(c > 99)
{
cerr << "分必须小于等于99" << endl;
exit(1);
}
amount = d * 100 + c;
if(s == minus) amount = -amount;
}
bool Money::Set(sign s, unsigned long d, unsigned long c)
//设置函数。s为符号, d为元值,c为分值
{
if(c > 99)
{
cerr << "分必须小于等于99" << endl;
false;
}
amount = d * 100 + c;
if(s == minus) amount = -amount;
return true;
}
Money Money::operator+(const Money& x) const //加运算符
{
Money y;
y.amount = amount + x.amount;
return y;
}
ostream& operator<<(ostream& out, const Money& x) //运算符<<重载
{
Money temp = x;
if(x.amount < 0 )
{
out << "-";
temp.amount = -temp.amount; //temp为x的绝对值
}
int d = temp.amount / 100; //d为amount的元值
out << "¥" << d << ".";
int c = temp.amount - d * 100; //c为amount的分值
if(c < 10) out << "0"; //分值小于10时在十位上添0
out << c;
return out;
}
//主函数部分
void main(void)
{
Money g, h(plus, 3, 30), hg;
g.Set(minus, 2, 25);
hg = h + g; //h和g的值均不变
g += h; //g的值被改变
cout << "h + g = " << hg <<endl; //可直接用运算符<<输出类hg
cout << "g = " << g << endl;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -