1 C++ 重载解引用_迭代器.cpp
#include<iostream>
#include<string.h>
using namespace std;
//实现迭代器的目的是可以进行泛型计算,比如使用范围for语句等等;
//实现迭代器的步骤:
//1,定义一个内部类iterator
//2,重载该内部类的!=, ++, *
//3,定义外部类的begin和end成员方法
class my_string{
private:
char* p=nullptr;
public:
class iterator{
int pos=0;
char * ip=nullptr;
public:
iterator(){};
iterator(char *i,int p)
:ip(i),pos(p){}
#if 0
iterator(iterator & i){
pos = i.pos;
ip = i.ip;
}
#endif
~iterator(){}
bool operator!=(iterator it)
{
return this->pos != it.pos;
}
iterator operator++()
{
pos++;
return *this;
}
char & operator*()
{
return ip[pos];
}
};
iterator begin()
{
return iterator(p,0);
}
iterator end()
{
return iterator(p,strlen(p));
}
my_string(){}
my_string(const char* s){
if(s){
p = new char[strlen(s)+1];
strcpy(p,s);
}
}
my_string( const my_string& ms){
if(ms.p){
if(p)delete []p;
p = new char[ms.size()+1];
strcpy(p,ms.p);
}
}
~my_string(){
if(p)delete [] p;
}
friend ostream &operator<<(ostream&cout,my_string &s);
char & operator[](int pos)
{
return p[pos];
}
int size()const{return strlen(p);}
my_string operator+(my_string s)
{
my_string tmp;
tmp.p= new char[this->size()+s.size()+1];
strcpy(tmp.p,this->p);
strcat(tmp.p,s.p);
return tmp;
}
my_string operator+(const char* s)
{
my_string tmp;
tmp.p= new char[this->size()+strlen(s)+1];
strcpy(tmp.p,this->p);
strcat(tmp.p,s);
return tmp;
}
//如果返回值和参数都是对象而不是引用,那么一定记得要先定义拷贝构造函数,而且该拷贝构造内部完成的是深拷贝
my_string operator=(my_string s)
{
if(this->p)delete[]p;
if(s.p){
p=new char[s.size()+1];
strcpy(this->p,s.p);
}else{
this->p = nullptr;
}
return *this;
}
};
ostream &operator<<(ostream&cout,my_string &s)
{
cout<<s.p;
return cout;
}
int main()
{
#if 0
string s="123";
string::iterator it;
// std::basic_string<char>::iterator it;
// for(auto k:s)
// char k;
for(it=s.begin();it != s.end();++it)
cout<<*it;
cout<<endl;
#else
my_string ms="123";
// my_string::iterator it;
// for(it=ms.begin();it != ms.end();++it)
// cout<<*it;
for(auto k:ms)
cout<<k;
cout<<endl;
#endif
return 0;
}