最近学习C++ 的基础知识,完成十进制转换为任意进制及操作符重载,在网上找的不错的资料,这里记录下,
实例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
#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;
}
|
运行结果:
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!