a trap in pointer moving

This problem has really troubled me for a long time.At first I pay much attention to the  operator function,but after a long-time  discussion with Teacher Song,we solved the problem. Yoo......



#include<iostream>
#include<cstring>
using namespace std;
class STRING
{
public:
    STRING(const char *str = "NULL")//constructor 

    {
            _pstr = new char[strlen(str)+1];
            strcpy(_pstr,str);
            cout<<"STRING(char)"<<endl;
    }


    STRING(const STRING& s)//deep constructor
    {
    _pstr=new char[strlen(s._pstr)+1];
        strcpy(_pstr, s._pstr);
        cout<<"String(const&)"<<endl;
    }


    ~STRING()//destructor

        if (_pstr)
        {
            delete[] _pstr;
            _pstr = NULL;
        }
        cout<<"~String()"<<endl;
    }


    STRING& operator=(const STRING& s)//deep operator
    {
        if(&s!=this )
        {
            if(_pstr) delete[] _pstr;//free memory
_pstr = new char[strlen(s._pstr) + 1];
strcpy(_pstr, s._pstr);
cout<<"String(operator)" <<endl;
        }
        
        return *this;
    }


    int Strlen()  // counter
    {
        int count = 0;
        char *p=_pstr;
        *_pstr=_pstr[0];
        while (*_pstr)
        {
            count++;
            _pstr++;
        }
        _pstr=p;
        return count;
    }
void Display()
{
cout<<_pstr<<endl;
}
private:
    char *_pstr;
};


int main()
{
   STRING s0,s1("abc");
   s0.Display();
   s1.Display();
  int m0=0,m1=0;
   m0=s0.Strlen();//the pointer has moved to  the end,point to NULL
   m1=s1.Strlen();

   cout<<"the length of s0:"<<m0<<endl<<"the length of s1:"<<m1;
   s0=s1;//it's useless,empty memory
   s0.Display();
  m0=s0.Strlen();
   cout<<"the length of s0:"<<m0<<endl;
   STRING s2=s1;
   s2.Display();
   int m2=0;
   m2=s2.Strlen();
   cout<<"the length of s2:"<<m2<<endl;
   return 0;
}


correct:

   int Strlen()  // counter
    {
        int count = 0;
       char *temp=_pstr;
        while (*_pstr)
        {
            count++;
            _pstr++;
        }
        _pstr=temp;//when finishing the function,remember to turn pointer  back to the first address,nor will make memory leak!
        return count;
    }

Details make!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值