具体代码
#include <iostream>
using namespace std;
class num
{
int val;
int length;
void calculate_length(){
if(val/10==0){
length=1;
return;
}
int x=10;
int pow=0;
int tempNum=val;
while(tempNum!=0){
tempNum/=10;
pow++;
}
length=pow;
}
public:
num(int tempNum)
{
val=tempNum;
calculate_length();
}
void set(int tempNum)
{
val = tempNum;
calculate_length();
}
int get()
{
return val;
}
class iterator
{
int pos;
num* obj;
public:
iterator(num* ptr,int n)
{
pos = n;
obj = ptr;
}
iterator()
{
pos = 0;
obj = nullptr;
}
void operator++(){
pos++;
}
void operator++(int i){
pos++;
}
void operator--(){
pos--;
}
void operator--(int i){
pos--;
}
int operator*()const{
if(pos>=obj->length) return -1;
if(pos==0)return obj->val%10;
int o=10;
int pow=0;
while(pow<(pos-1)){
o*=10;
pow++;
}
return (obj->val%(o*10))/(o);
}
bool operator!=(const iterator& it){
return it.pos!=pos;
}
bool operator==(const iterator& it){
return it.pos==pos;
}
};
iterator begin()
{
return iterator(this,0);
}
iterator end()
{
return iterator(this,length);
}
};
int main()
{
num a(2354862);
for(auto it=a.begin();it!=a.end();it++){
cout<<*it<<" ";
}
cout<<endl;
return 0;
}
参考资料
https://blog.csdn.net/dyyzlzc/article/details/103336232