c++ 错在哪里?

来源:百度知道 编辑:UC知道 时间:2024/06/16 22:27:44
//str1.h
#include <iostream.h>
#include <string.h>
class str{private:char *string;
public:str(char* s){string=new char[strlen(s)+1];strcpy(string,s);}
~str(){cout<<"Delete…"<<endl;delete string;}
void print(){cout<<string<<endl;}};
#include "str1.h"
void main(){str s1="student";str s2=s1;
s1.print();s2.print();}

str s2=s1;
语句中你没有定义复制构造函数,所以编译系统会用浅复制。你需要在类中增加一个复制构造函数。
str(const str &s)
{
string = new char[strlen(s.string) + 1];
strcpy(string, s.string);
}

其实你的类中最好还要增加一个赋值函数
str& operator=(const str &s)
{
if(this != &s)
{
string = new char[strlen(s.string) + 1];
strcpy(string, s.string);
}
return *this;
}