Convert decimal to any base and overload Operators

Source: Internet
Author: User

# Include <iostream> # include <vector> # include <limits> using namespace std; using std: iterator; /// <summary> /// convert the decimal format to any hexadecimal format. to familiarize yourself with the operators, the operator overload is also added. /// Include auto increment (++), operator weight (+), value assignment function overload (=), and output operator (<) /// </summary> class TenToAny {vector <char> value; long _ n; long _ x; public: TenToAny (): _ n (10 ), _ x (0) {} void Switch () {try {int x = _ x, n = _ n; char flag = ''; if (x> LONG_MAX | x <LONG_MIN) throw "overflow"; if (x <0) {flag = '-'; x =-x;} while (x! = 0) {long remain = x % n; x = x/n; if (remain> = 10) remain = 'A' + remain % 10; else remain + = '0'; value. push_back (remain);} vector <char >:: reverse_iterator v = value. rbegin (); while (* v = '0') value. pop_back (); if (flag = '-') value. push_back (flag);} catch (char * e) {cout <e <endl ;}} TenToAny (long n, long x) {_ n = n; _ x = x; Switch () ;}tentoany & operator = (const TenToAny & num) {if (this = & num) return * this; value = num. Value; _ n = num. _ n; _ x = num. _ x; return * this;} TenToAny operator + (const TenToAny & num1) {TenToAny num; num. _ x = num1. _ x + _ x; num. _ n = num1. _ n; num. switch (); return num;} TenToAny & operator ++ () // frontend ++ {_ x ++; value. clear (); this-> Switch (); return * this;} TenToAny & operator ++ (int) // post ++ {TenToAny * temp = new TenToAny (this-> _ n, this-> _ x); _ x ++; value. clear (); this-> Switch (); return * temp;} friend ostream & operator <(ostream & ou T, TenToAny num) ;}; ostream & operator <(ostream & out, TenToAny num) {vector <char> value = num. value; vector <char >:: reverse_iterator v = value. rbegin (); for (; v! = Value. rend (); v ++) {out <* v;} return out;} int main () {TenToAny num (19,111); TenToAny copy (19,222); TenToAny sum; sum = num + copy; cout <num <endl; cout <copy ++ <endl; cout <(++ copy) <endl; return 0 ;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.