C++ <使用函数运算符重载执行类对象加法>
来源:互联网 发布:linux 多核cpu使用率 编辑:程序博客网 时间:2024/06/12 23:18
运行结果:
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
- C++ <使用函数运算符重载执行类对象加法>
- c++语言 运算符重载 使用重载运算符实现类的加法运算
- 【C/C++学院】0820-Nullptr/const对象/类指针引用以及mallocfree与newde/类重载运算符/QT加法重载/类的重载赋值运算/自增在前在后差别/赋值重载深浅拷贝/重载下标
- 使用运算符重载实现复数的加法运算
- C++:重载函数运算符
- 【C++】重载运算符和重载函数
- C++:运算符重载1(分数的加法)
- 类于内联函数,外联函数,运算符重载以及类对象的使用
- 【c++】类和对象--四个默认成员函数+运算符重载
- 【C++】类和对象--基础知识+四个默认成员函数+运算符重载
- C++ 运算符重载之把类对象当着函数名使用
- 类和对象(四个默认成员函数+运算符重载)
- 类和对象->四个默认成员函数->运算符重载
- 《类和对象+四个默认函数+运算符重载》
- CPP类和对象--四个默认函数+运算符重载
- 无名对象简化运算符重载函数
- 【c++】关于类继承运算符重载友元函数
- 【C++】之【运算符重载函数】
- 数据结构中树的表示方法
- Asp.Net Application和Session内置对象讲解
- 面向对象的编程就是在创造世界(一)
- android.手机短信发送器
- 对数据库中数据库系统的结构的认识
- C++ <使用函数运算符重载执行类对象加法>
- Java中构造方法与重载
- JavaScript序列化和反序列化
- Linux进程理解与实践(三)进程终止函数和exec函数族的使用
- 算法的基本概念
- HashMap Hashtable区别
- OS X10.8.5下安装XCode3.2.5重启导致系统崩溃
- LOJ1379限制性最路算法应用
- spring-loader 热部署