分配内存错误

来源:互联网 发布:淘宝卖家app叫什么 编辑:程序博客网 时间:2024/06/05 23:46
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <malloc.h>
using namespace std;
class myString{


public:
    char* pStr;
    myString(const char* p)
    {
     pStr = new char[20];//此处不能使用(),使用()只会创建一个空间
     pStr = (char*)malloc(20);
     strcpy(pStr,p);
    }


    myString& operator+(const myString&  rhs)
    {


    cout<<strlen(rhs.pStr)<<"\t"<<strlen(pStr)<<endl;
    char * temp = new char(41);


    strcpy(temp,pStr);


    strcat(temp,rhs.pStr);


    delete pStr;
    pStr = temp;
    cout <<pStr<<endl;
    return *this;
    }


};
int main ()
{
  char str1[]={"Sampletring1"};
  char str2[40];
  char str3[]={"Sampletring2"};


  myString pA(str1);
  myString pB(str1);
  myString pC(str3);
  cout<<pA.pStr<<endl;
  cout<<pB.pStr<<endl;
  cout<<pC.pStr<<endl;
  //pA +pA;
  return 0;
}
原创粉丝点击