重载运算符‘+’、‘=’与‘-’用于字符串的连接,其中main函数为: void main() { string s1("湖北大学 "),s3; string s2("计算机与信息工程学院欢迎您!"); s3=s1+s2; s3.display(); s3=s1-s2; s3.display(); } 要求运行结果为: 湖北大学 计算机学院欢迎您! 湖北大学计算机学院欢迎您!
时间: 2024-01-09 15:05:57 浏览: 30
下面是代码实现:
```
#include<iostream>
#include<string>
using namespace std;
class string_concat {
private:
string s;
public:
string_concat(string str=""):s(str){} //构造函数
string_concat operator + (string_concat &str) { //重载运算符 "+"
string res = s + str.s;
return string_concat(res);
}
string_concat operator - (string_concat &str) { //重载运算符 "-"
string res = s;
int pos = res.find(str.s);
if(pos != -1) res.erase(pos, str.s.size());
return string_concat(res);
}
void display() { //输出字符串
cout << s << endl;
}
};
int main() {
string_concat s1("湖北大学 ");
string_concat s2("计算机学院欢迎您!");
string_concat s3;
s3 = s1 + s2; //连接字符串
s3.display();
s3 = s1 - 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://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)
![dll](https://img-home.csdnimg.cn/images/20210720083646.png)