C++ <使用函数运算符重载执行类对象加法>

运行结果:

 Enter the first money (dollars): 12.123
 Invalid dollars and cents, negative values

 Enter the first money (dollars): 33.99
 Enter the second money (dollars): 35.33
 The sum is: $69.32

AltMoney.h

#ifndef __frendFuciton__AltMoney__
#define __frendFuciton__AltMoney__

class AltMoney {
private:
    int dollars;
    int cents;
public:
    AltMoney();
    AltMoney(int dollars, int cents);
    AltMoney operator+(const AltMoney& m);
    void show();
};

#endif 

AltMoney.cpp

#include "AltMoney.h"
#include <iostream>

AltMoney::AltMoney() {
    dollars = cents = 0;
}

AltMoney::AltMoney(int dollars, int cents) {
    this->dollars = dollars;
    this->cents = cents;
}

AltMoney AltMoney::operator+(const AltMoney& m) {
    const int CENTS_PER_DOLLAR = 100;
    AltMoney sum;

    sum.cents = cents + m.cents;
    int count = sum.cents / CENTS_PER_DOLLAR;
    sum.cents %= CENTS_PER_DOLLAR;

    sum.dollars = dollars + m.dollars + count;

    return sum;
}

void AltMoney::show() {
    std::cout << "The sum is: " << "$" << dollars << "." << cents;
}

operateOverFlow.cpp

#include "AltMoney.h"
#include <iostream>
#include <cstdlib>

void readMoney(int& dollars, int& cents);

int main() {
    using std::cout;
    using std::cin;

    AltMoney sum;
    int dollars, cents;

    cout << "Enter the first money (dollars): ";
    readMoney(dollars, cents);
    AltMoney m1(dollars, cents);

    cout << "Enter the second money (dollars): ";
    readMoney(dollars, cents);
    AltMoney m2(dollars, cents);

    sum = m1 + m2;
    sum.show();

    return 0;
}

void readMoney(int& dollars, int& cents) {
    using std::cout;
    using std::cin;

    cin >> dollars;
    cin.get();
    cin >> cents;

    if (dollars < 0 || cents < 0 || cents >=100 ) {
        cout << "Invalid dollars and cents, negative values\n";
        exit(EXIT_FAILURE);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值