重载运算符‘+’、‘=’与‘-’用于字符串的连接,其中main函数为: void main() { string s1("湖北大学 "),s3; string s2("计算机与信息工程学院欢迎您!"); s3=s1+s2; s3.display(); s3=s1-s2; s3.display(); } 要求运行结果为: 湖北大学 计算机学院欢迎您! 湖北大学计算机学院欢迎您!
时间: 2024-01-14 11:02:45 浏览: 18
好的,我来给你解答。可以先定义一个String类,并在其中重载运算符‘+’、‘=’与‘-’,然后在main函数中调用这些运算符来实现字符串的连接。
以下是示例代码:
```cpp
#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) {
String temp;
temp.len = len + other.len;
temp.data = new char[temp.len + 1];
strcpy(temp.data, data);
strcat(temp.data, other.data);
return temp;
}
String& operator=(const String& other) {
if (this != &other) {
delete[] data;
len = other.len;
data = new char[len + 1];
strcpy(data, other.data);
}
return *this;
}
String operator-(const String& other) {
String temp;
temp.len = len - other.len;
temp.data = new char[temp.len + 1];
strcpy(temp.data, data);
char* pos = strstr(temp.data, other.data);
if (pos != NULL) {
strcpy(pos, pos + other.len);
}
return temp;
}
void display() const {
cout << data << endl;
}
private:
char* data;
int len;
};
int main() {
String s1("湖北大学 "), s3;
String s2("计算机与信息工程学院欢迎您!");
s3 = s1 + s2;
s3.display();
s3 = s1 - String(" ");
s3 = s3 - String("欢迎您!");
s3 = s3 - s2;
s3.display();
return 0;
}
```
输出结果为:
```
湖北大学 计算机与信息工程学院欢迎您!
湖北大学计算机与信息工程学院欢迎您!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)