C++编程问题!紧急!!

来源:百度知道 编辑:UC知道 时间:2024/05/30 18:32:09
写完以后有一个错误,不知道怎么改,大家帮帮忙啊!谢谢!

设计一个字符串类重载“+=”运算符,使其实现两个字符串的连接并赋值。

#include<iostream.h>
#include<string.h>
class String{
public:
String(){p=NULL;}
String(char *str){p=str;}
friend String operator+=(String &string1,String &string2);
private:
char *p;
};

String operator+=(String &string1,String &string2)
{return strcat(string1.p,string2.p);
}

void main()
{String string1("I am ");
String string2("the best!");
cout<<(string1+=string2)<<endl;
}

#include<iostream.h>
#include<string.h>

class String {
friend ostream& operator<<(ostream& output, String& string);
public:
String() {
p=NULL;
len=0;
p=new char[len+1];
strcpy(p, ""); //默认构造一个空串
}
String(char *str) {
len=strlen(str);
p=new char[len+1];
strcpy(p, str);
}
~String() {
delete[] p; //记得释放动态分配的内存
}
String& operator+=(String &string); //用成员函数更好一些
private:
char *p;//最好用动态分配
int len;
};

ostream& operator<<(ostream& output, String& string)
{
output << string.p;
return output;
}

String& String::operator+=(String &string)
{
char* temp=p;
len+=string.len;
p=new char[len+1];
strcpy(p,temp);
strcat(p,string.p);