用c++实现:设计一个字符串类重载“+=”运算符,使其实现两个字符串的连接并赋值。试分别用成员函数和友元函数实现。
时间: 2023-11-27 14:55:08 浏览: 75
成员函数实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class String {
public:
String(const char* str = "") {
len = strlen(str);
data = new char[len + 1];
strcpy(data, str);
}
String(const String& other) {
len = other.len;
data = new char[len + 1];
strcpy(data, other.data);
}
~String() {
delete[] data;
}
String& operator+=(const String& other) {
char* temp = new char[len + other.len + 1];
strcpy(temp, data);
strcat(temp, other.data);
delete[] data;
data = temp;
len += other.len;
return *this;
}
void print() {
cout << data << endl;
}
private:
char* data;
int len;
};
int main() {
String s1("hello");
String s2("world");
s1 += s2;
s1.print();
return 0;
}
```
友元函数实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class String {
public:
String(const char* str = "") {
len = strlen(str);
data = new char[len + 1];
strcpy(data, str);
}
String(const String& other) {
len = other.len;
data = new char[len + 1];
strcpy(data, other.data);
}
~String() {
delete[] data;
}
friend String operator+(const String& str1, const String& str2) {
String result;
result.len = str1.len + str2.len;
result.data = new char[result.len + 1];
strcpy(result.data, str1.data);
strcat(result.data, str2.data);
return result;
}
void print() {
cout << data << endl;
}
private:
char* data;
int len;
};
int main() {
String s1("hello");
String s2("world");
String s3 = s1 + s2;
s3.print();
return 0;
}
```
阅读全文