- 论坛徽章:
- 0
|
- 请问这个代码中:
- #include<iostream.h>
- #include<string.h>
- class string{
- char *ptr;
- public:
- string (char *s)
- {ptr=new char[strlen(s)+1];
- strcpy(ptr,s);
- }
- ~string()
- {delete ptr;}
- void print()
- {cout<<ptr<<endl;}
- string &operator=(string &;
- };
- string &string:perator = (string &s)
- {
- if(this==&s) return *this;
- delete ptr;
- ptr=new char[strlen(s.ptr)+1];
- strcpy(ptr,s.ptr );
- return *this;
- }
- int main()
- {
- string p1("chen";
- {
- string p2(" ";
- p2=p1;
- cout<<"p2:";
- p2.print();
- }
- cout<<"p1:";
- p1.print() ;
- return 0;
- }
- 将string &operator=(string &;改为string operator=(string &;
- 将string &string:perator = (string &s)
- {
- if(this==&s) return *this;
- delete ptr;
- ptr=new char[strlen(s.ptr)+1];
- strcpy(ptr,s.ptr );
- return *this;
- }
- 改为string string:perator = (string &s)
- {
- if(this==&s) return *this;
- delete ptr;
- ptr=new char[strlen(s.ptr)+1];
- strcpy(ptr,s.ptr );
- return *this;
- }
- 运行结果为什么不一样呢?
复制代码 |
|