a trap in pointer moving

来源:互联网 发布:尼康 35 1.8 知乎 编辑:程序博客网 时间:2024/05/22 00:15

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!

原创粉丝点击