C++编程题,要所有代码加注释,急求!

2024-11-20 08:02:30
推荐回答(1个)
回答1:

#include
using namespace std;
class Money
{
public:
Money(int pYuan=0, int pJiao=0, int pFen=0);
Money& operator + (Money& money);
Money& operator-(Money& money); //也可以用友元函数实现
void operator=(Money& money); //赋值运算符只能作为成员函数,而不能做友元函数
friend ostream& operator<<(ostream& output, Money& money);
private:
int yuan;
int jiao;
int fen;
};
Money::Money(int pYuan, int pJiao, int pFen)
{
yuan = pYuan;
jiao = pJiao;
fen = pFen;
}
Money& Money::operator +(Money& money)
{
int yuan;
int jiao;
int fen;
yuan = this->yuan + money.yuan;
jiao = this->jiao + money.jiao;
fen = this->fen + money.fen;
if(fen >= 10)
{
jiao += 1;
fen -= 10;
}
if(jiao >= 10)
{
yuan += 1;
jiao -= 10;
}
return Money(yuan, jiao, fen);
}

Money& Money::operator-(Money& money)
{
int yuan;
int jiao;
int fen;
fen = this->fen - money.fen;
if(fen < 0)
{
this->jiao -= 1;
fen += 10;
}
jiao = this->jiao - money.jiao;
if(jiao < 0)
{
this->yuan -= 1;
jiao += 10;
}
yuan = this->yuan - money.yuan;

return Money(yuan, jiao, fen);
}

void Money::operator=(Money& money)
{
yuan = money.yuan;
jiao = money.jiao;
fen = money.fen;
}
ostream& operator<<(ostream& output,Money& money)
{
output< return output;
}

void main()
{
Money money1(3,6,4);
Money money2(1,7,9);
Money money3;
Money money4;
Money money5;
money3=money1+money2;
money4=money1-money2;
money5=money4;
cout< cout< cout<}
在VS2005中编译没问题,如果在VC6.0中有问题将头两行换为
#include即可