String String::operator + (const char* s)const { String ret; long long len = m_length + strlen(s ? s : ""); char* new_str = reinterpret_cast<char*>(malloc(len+1)); if(new_str) { strcpy(new_str,m_str); strcat(new_str,s ? s : ""); free(ret.m_str); ret.m_str = new_str; ret.m_length = len;} else {//THROW_EXCEPTION(NoEnoughMemoryException,"No memory to creat new element ..."); cout<<"没有足够的内存异常,“没有内存来创建新元素"<<endl; }return ret;}
时间: 2024-03-18 19:43:50 浏览: 28
这是一个 C++ 中的字符串类 String 中的重载运算符 +,其作用是将两个字符串进行连接。具体实现如下:
1. 首先创建一个新的 String 对象 ret,用于存储连接后的字符串;
2. 然后计算出连接后的字符串的长度,为原有字符串 m_str 的长度加上第二个字符串 s 的长度(如果 s 为空,则将长度置为 0);
3. 分配空间,将原有字符串 m_str 和第二个字符串 s 拼接起来,并存储到新的内存空间 new_str 中;
4. 如果内存分配成功,将 ret 对象中原有的字符串 m_str 释放,并将新的内存空间 new_str 赋值给 ret 对象的 m_str 成员变量,并更新 ret 对象的 m_length 成员变量;
5. 如果内存分配失败,则输出错误信息并抛出异常;
6. 最后返回新的 String 对象 ret。
需要注意的是,在第 3 步中,如果第二个字符串 s 为空,则需要将长度置为 0,否则使用 strlen() 函数计算字符串长度时会出现错误。同时,在第 4 步中,需要释放 ret 对象中原有的字符串 m_str,否则会造成内存泄漏。
相关问题
String operator+ (const char* c, const String& s)
这是一个重载了加号运算符的函数,它允许在一个字符串常量和一个String对象之间进行拼接操作。具体来说,这个函数的定义是将一个字符串常量c和一个String对象s拼接起来,返回一个新的String对象,新的String对象中包含了c和s两个字符串的内容。
例如,如果我们有一个String对象s1,它的值为"Hello",我们想要将一个字符串常量"c++"拼接到s1的后面,我们可以这样做:
```
String s1("Hello");
String s2 = "c++";
String s3 = s2 + s1;
```
这样,s3的值就是"c++Hello"。在这个例子中,我们使用了重载了加号运算符的函数String operator+ (const char* c, const String& s),将字符串常量"c++"和String对象s1拼接起来得到了s3。
bool String::operator == (const char* s)const {return (strcmp(m_str,s ? s : "") == 0);}
这是一个字符串类中的重载运算符==,用于判断当前对象和传入的C风格字符串是否相等。具体实现是调用了C标准库函数strcmp(),比较当前对象的m_str成员和传入的s指针指向的字符串是否相等。如果相等返回0,否则返回非0值。需要注意的是,为了避免传入的s指针为NULL,代码中使用了三目运算符将其转为空字符串。
相关推荐
![hpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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://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)