首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

why this one cannot work(sorry ,something wrong with chinese)解决方案

2012-03-24 
why this one cannot work(sorry ,something wrong with chinese)that is the program below:#include st

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)不对。

热点排行