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!
- a trap in pointer moving
- CodeForces 840E. In a Trap
- Implementing a simple smart pointer in c++
- Implementing a simple smart pointer in C++
- pointer to a function used in arithmetic
- Implementing a simple smart pointer in C++
- A trap of parameter ‘size_average’ in pytorch 详解
- Moving items up and down in a ListView control
- Moving ASM spfile to a shared device in RAC
- Moving ASM spfile to a shared device in RAC
- Trap in Unix
- trap in shell
- Trap in bash
- How to set NULL to a pointer in Managed C++?
- How to use the pointer of function in a class?
- [leetcode] populating next right pointer in a binary tree
- A moving English song
- Alignment trap: in ARM architecture .
- GlusterFS创建volume失败的解决方法(* or a prefix of it is already part of a volume)
- Android tablayout集合fragment使用
- 远程连接Linux系统下MySQL数据库失败解决方法
- CentOS6.9用yum安装gccError:Cannot find a valid baseurl for repo:base。用yum装httpd80端口被占用。
- Spark基本术语表+基本架构+基本提交运行模式
- a trap in pointer moving
- Python -range 与xrange
- 使用枚举定义常量
- itext打印PDF
- centos系统下安装javaJDK
- Android 嵌套滑动——NestedScrolling完全解析
- vue.js实现数据驱动视图原理
- 【一道数学题】从(0,0)点经过(x,y)点到达(a,b)点的最短路径有多少条
- Hanoi拓展(java)