2 a1798826049 a1798826049 于 2014.11.07 16:13 提问

似乎是析构函数出问题

#include
#include
using namespace std;
#ifndef _String_h
#define _String_h
class String{
public:
String(char *s=NULL);
//~String();
String operator+( String &cs);
void display();
private:
char *str;
};
String::String(char *s){
if (s==NULL){
str = new char[1];
str= '\0';
}
else{
int length = strlen(s)+1;
str = new char[length ];
strcpy_s(str,length, s);
}

};
/*String::~String(){
cout << "diao yong xigou" << endl;
delete []str;
}*/

String String::operator+(String &cs){
String newstr;
int l = strlen(str) + strlen(cs.str)+1;
newstr.str = new char[l];
strcpy_s(newstr.str,l, str);
strcat_s(newstr.str,l, cs.str);
return newstr;
}

void String::display(){
cout << str << endl;
}
#endif
#include "String.h"
int main(){
String c1("obj"),c2("ect"),c3;
cout << "c1="; c1.display();
cout << "c2="; c2.display();
c3 = c1 + c2;
cout << "c3="; c3.display();
return 0;

}

没注视掉析构函数运行出错,在c1.display时会调用析构函数,但我下面还要c1,为何会调用析构函数呢,但注释后可以运行成功,但没有delete释放内存,不知内存会被释放不.

Csdn user default icon
上传中...
上传图片
插入图片