C++ <使用友元函数的类对象加法>

运行结果:

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

 Enter the first money (dollars): 12.21
 Enter the second money (dollars): 99.99
 The sum is: $112.20

altMoney.h

#ifndef __frendFuciton__altMoney__
#define __frendFuciton__altMoney__

class altMoney {
private:
    int dollars;
    int cents;
public:
    altMoney();
    altMoney(int dollars, int cents);
    // 友元函数与普通类函数的区别在于,调用友元函数的方法与普通函数相同,类函数则必须是类对象才能调用 
    friend void add(const altMoney& m1, const altMoney& m2, altMoney& sum);
    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;
}

void add(const altMoney& m1, const altMoney& m2, altMoney& sum) {
    const int CENTS_PER_DOLLAR = 100;

    sum.cents = m1.cents + m2.cents;
    int count = sum.cents / CENTS_PER_DOLLAR;
    sum.cents %= CENTS_PER_DOLLAR;

    sum.dollars = m1.dollars + m2.dollars + count;
}

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

friendFouction.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);

    add(m1, m2, sum);
    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、付费专栏及课程。

余额充值