C++ 基礎(chǔ)編程之十進(jìn)制轉(zhuǎn)換為任意進(jìn)制及操作符重載
更新時(shí)間:2017年02月15日 14:48:52 投稿:lqh
這篇文章主要介紹了C++ 基礎(chǔ)編程之十進(jìn)制轉(zhuǎn)換為任意進(jìn)制及操作符重載的相關(guān)資料,需要的朋友可以參考下
C++ 基礎(chǔ)編程之十進(jìn)制轉(zhuǎn)換為任意進(jìn)制及操作符重載
最近學(xué)習(xí)C++ 的基礎(chǔ)知識,完成十進(jìn)制轉(zhuǎn)換為任意進(jìn)制及操作符重載,在網(wǎng)上找的不錯(cuò)的資料,這里記錄下,
實(shí)例代碼:
#include<iostream> #include<vector> #include<limits> using namespace std; using std::iterator; ///<summary> ///十進(jìn)制轉(zhuǎn)換為任意進(jìn)制,為了熟悉操作符,也加了操作符重載。 ///包括自增(++),運(yùn)算符重(+),賦值函數(shù)重載(=),輸出符(<<) ///</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; }
運(yùn)行結(jié)果:
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
opencv2基于SURF特征提取實(shí)現(xiàn)兩張圖像拼接融合
這篇文章主要為大家詳細(xì)介紹了opencv2基于SURF特征提取實(shí)現(xiàn)兩張圖像拼接融合,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03C++開發(fā)protobuf動(dòng)態(tài)解析工具
這篇文章主要為大家介紹了C++開發(fā)protobuf動(dòng)態(tài)解析工具實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01C語言詳細(xì)分析講解關(guān)鍵字const與volatile的用法
在C語言中,我們經(jīng)常會見到const和volatile這兩個(gè)關(guān)鍵字,那么我們今天就來介紹下這兩個(gè)關(guān)鍵字,提起?const?關(guān)鍵字,我們可能首先想到的是經(jīng)過它修飾的變量便是常量了。其實(shí)我們這種想法是錯(cuò)誤的,其實(shí)?const?修飾的變量是只讀的,其本質(zhì)還是變量2022-04-04