写了一个简单的String类,重载了加号和等号,等号可以直接一对一赋值,但加了再赋值就不行。代码如下,请指教
#include<iostream>
#include<cString>
using namespace std;
class String {
char *str;
int len;
public:
String(char *s = 0) {
if(s) {
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
else {
len = 0;
str = 0;
}
}
String(String &s) {
if(s.str) {
len = s.len;
str = new char[len + 1];
strcpy(str, s.str);
}
else {
len = 0;
str = 0;
}
}
~String() {
if(str != NULL) delete []str;
}
void show() {
if(str) cout<<str<<endl;
else cout<<"this string is empty"<<endl;
}
String &operator =(String s){
if(str) delete []str;
if(s.str) {
len = s.len;
str = new char[len + 1];
strcpy(str, s.str);
}
else {
len = 0;
str = 0;
}
return *this;
}
friend String &operator +(String &, String &);
};
String operator +(String &s1, String &s2) {
String temp;
temp.len = s1.len + s2.len;
temp.str = new char[temp.len + 1];
strcpy(temp.str, s1.str);
strcat(temp.str, s2.str);
return temp;
}
int main() {
char *a="C plus plus ";
String s1(a), s2("language"), s3;//测试两种构造函数
s1.show( );
s2.show( );
s3 = s1 + s2; //此行报错
s3.show( );
}
报错为 [Error] no matching function for call to 'String::String(String)'