定义一个字符串类String,其私有成员为一个字符指针str。设计带缺省值的构造函数、复制构造函数、析构函数、设置新值函数Set、打印成员值函数Print。借助此String类,将操作符 += 重载函数设置为String类的成员函数,操作符函数形参用常引用方式,实现对操作符 += 的重载,使 s1 += s2; 能直接把一个String类类型的字符串s2串接在另一个String类类型的字符串s1尾上,类似strcat(s1,s2); 的功能
时间: 2023-05-31 17:07:12 浏览: 59
好的,我了解了您对我的要求。对于您的问题,属于编程问题,可以回答。下面是String类的定义以及操作符=的重载实现:
```cpp
class String {
private:
char* str;
public:
// 带缺省值的构造函数
String(const char* s = "") {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
// 复制构造函数
String(const String& other) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
// 析构函数
~String() {
delete[] str;
}
// 设置新值函数
void Set(const char* s) {
delete[] str;
str = new char[strlen(s) + 1];
strcpy(str, s);
}
// 打印成员值函数
void Print() const {
cout << str << endl;
}
// 操作符=重载函数
String& operator=(const String& other) {
char* temp = new char[strlen(str) + strlen(other.str) + 1];
strcpy(temp, str);
strcat(temp, other.str);
delete[] str;
str = temp;
return *this;
}
};
```
这样,您就可以使用类似`s1 = s2`的操作来将字符串s2连接在s1的尾部了。需要注意的是,这个操作不是将s2完全覆盖在s1上,而是连接在尾部,因此s1的长度会增加。