运行结果:
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);
}
}