读书人

why this one cannot work(sorry ,som

发布时间: 2012-03-24 14:00:46 作者: rapoo

why this one cannot work(sorry ,something wrong with chinese)
that is the program below:
#include <stdio.h>
#include <string.h>
//using namespace std;

class mystring
{
public:
mystring(mystring &str){
if(m_str!=NULL){
delete [] m_str;
}
m_str=new char[strlen(str.m_str)+1];
strcpy(m_str,str.m_str);
}
mystring &operator=(const char *str){
if(m_str!=NULL){
delete [] m_str;
}
m_str=new char[strlen(m_str)+1];
strcpy(m_str,str);
return *this;
}
mystring(){
m_str=NULL;
}
~mystring(){
delete [] m_str;
}
private:
char *m_str;
};
int main(int argc,char * argv[]){
mystring str1;
str1="hello world";
mystring str2;
str2 =str1;
mystring str3=str2;
return 0;
}

after debug,it says segment default .what is wrong with str1="hello world";

[解决办法]

C/C++ code
#include  <stdio.h > #include  <string.h > //using namespace std; class mystring { public:     mystring(mystring &str){         m_str = new char[strlen(str.m_str)+1];         strcpy(m_str,str.m_str);     }     mystring &operator=(const char *str){         if(m_str!=NULL){             delete [] m_str;         }         m_str=new char[strlen(str)+1];         strcpy(m_str,str);         return *this;     }     mystring &operator=(mystring &str){         if(m_str!=NULL){             delete [] m_str;         }         m_str = new char[strlen(str.m_str)+1];         strcpy(m_str,str.m_str);        return *this;     }     mystring(){         m_str=NULL;     }     ~mystring(){         delete [] m_str;     } private:     char *m_str; }; int main(int argc,char * argv[]){     mystring str1;     str1="hello world";     mystring str2;     str2 =str1;     mystring str3=str2;     return 0; }
[解决办法]
mystring &operator=(const char *str){
if(m_str!=NULL){
delete [] m_str;
}
m_str=new char[strlen(m_str)+1];
strcpy(m_str,str);
return *this;
}
这里strlen(m_str)不对。

读书人网 >C++

热点推荐