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; }
运行结果:
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。