C++ 基礎編程之十進制轉換為任意進制及操作符重載。本站提示廣大學習愛好者:(C++ 基礎編程之十進制轉換為任意進制及操作符重載)文章只能為提供參考,不一定能成為您想要的結果。以下是C++ 基礎編程之十進制轉換為任意進制及操作符重載正文
C++ 基礎編程之十進制轉換為任意進制及操作符重載
最近學習C++ 的基礎知識,完成十進制轉換為任意進制及操作符重載,在網上找的不錯的資料,這裡記錄下,
實例代碼:
#include<iostream> #include<vector> #include<limits> using namespace std; using std::iterator; ///<summary> ///十進制轉換為任意進制,為了熟悉操作符,也加了操作符重載。 ///包括自增(++),運算符重(+),賦值函數重載(=),輸出符(<<) ///</summary> class TenToAny { vector<char> value; long long _n; long 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 "溢出"; if(x<0) { flag='-'; x=-x; } while(x!=0) { long 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 long n,long 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 ++()//前置++ { _x++; value.clear(); this->Switch(); return *this; } TenToAny &operator ++(int)//後置++ { TenToAny *temp=new TenToAny(this->_n,this->_x); _x++; value.clear(); this->Switch(); return *temp; } friend ostream &operator <<(ostream &out,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; cout<<(++copy)<<endl; return 0; }
運行結果:
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!