当前位置: 首页 > news >正文

string 类运算符重载

目录

一、赋值运算符 (=)

二、复合赋值运算符 (+=)

三、字符串连接运算符 (+)

四、流操作运算符 (>> 和 <<)

工作原理:

五、关系比较运算符

boolalpha 的基本作用

六、总结表


一、赋值运算符 (=)

string 类重载了赋值运算符,支持多种类型的赋值操作。

string& operator=(const string& str);      // string对象赋值
string& operator=(const char* s);         // C风格字符串赋值
string& operator=(char c);                // 单个字符赋值
string& operator=(initializer_list<char> il);  // 初始化列表赋值 (C++11)

示例代码:

#include <iostream>
#include <string>
using namespace std;int main() {string s1;string s2("CSDN");// 1. string对象赋值s1 = s2;cout << s1 << endl;  // 输出: CSDN// 2. C风格字符串赋值s1 = "hello world";cout << s1 << endl;  // 输出: hello world// 3. 单个字符赋值s1 = 'A';cout << s1 << endl;  // 输出: A// 4. 初始化列表赋值 (C++11)s1 = {'C', 'P', 'P'};cout << s1 << endl;  // 输出: CPPreturn 0;
}


二、复合赋值运算符 (+=)

string 类重载了 += 运算符,支持多种类型的追加操作。

string& operator+=(const string& str);    // 追加string对象
string& operator+=(const char* s);       // 追加C风格字符串
string& operator+=(char c);              // 追加单个字符
string& operator+=(initializer_list<char> il);  // 追加初始化列表 (C++11)

示例代码:

#include <iostream>
#include <string>
using namespace std;int main() {string s1("Hello");string s2(" CSDN");// 1. 追加string对象s1 += s2;cout << s1 << endl;  // 输出: Hello CSDN// 2. 追加C风格字符串s1 += ", welcome!";cout << s1 << endl;  // 输出: Hello CSDN, welcome!// 3. 追加单个字符s1 += '!';cout << s1 << endl;  // 输出: Hello CSDN, welcome!!// 4. 追加初始化列表 (C++11)s1 += {' ', ':', ')'};cout << s1 << endl;  // 输出: Hello CSDN, welcome!! :)return 0;
}


三、字符串连接运算符 (+)

string 类重载了 + 运算符,支持多种字符串连接组合。

string operator+(const string& lhs, const string& rhs);  // string + string
string operator+(const string& lhs, const char* rhs);   // string + C字符串
string operator+(const char* lhs, const string& rhs);   // C字符串 + string
string operator+(const string& lhs, char rhs);          // string + 字符
string operator+(char lhs, const string& rhs);          // 字符 + string
string operator+(string&& lhs, string&& rhs);           // 右值引用版本

C++ 中的 string 类的 + 运算符被设计为不修改原对象,而是返回一个新的 临时string 对象

示例代码:

#include <iostream>
#include <string>
using namespace std;int main() {string s1("Super");string s2("Man");const char* cstr = "Woman";char ch = '!';// 1. string + stringcout << (s1 + s2) << endl;      // 输出: SuperMan// 2. string + C字符串cout << (s1 + cstr) << endl;    // 输出: SuperWoman// 3. C字符串 + stringcout << (cstr + s1) << endl;    // 输出: WomanSuper// 4. string + 字符cout << (s1 + ch) << endl;      // 输出: Super!// 5. 字符 + stringcout << (ch + s1) << endl;      // 输出: !Super// 6. 链式连接cout << (s1 + " " + s2 + ch) << endl;  // 输出: Super Man!return 0;
}


四、流操作运算符 (>> 和 <<)

string 类重载了流操作运算符,支持直接的输入输出。

istream& operator>>(istream& is, string& str);   // 输入运算符
ostream& operator<<(ostream& os, const string& str);  // 输出运算符

示例代码:

#include <iostream>
#include <string>
using namespace std;int main() {string name;cout << "请输入您的名字: ";cin >> name;  // 使用重载的>>运算符cout << "您好, " << name << "!" << endl;  // 使用重载的<<运算符// 读取一行输入cout << "请输入一句话: ";cin.ignore();  // 清除之前的换行符getline(cin, name);  // 使用getline读取整行cout << "您输入的是: " << name << endl;return 0;
}

工作原理:

  1. cin.ignore()

    • 清除输入缓冲区中残留的换行符(\n

    • 这是因为之前的 cin >> 操作会在缓冲区留下换行符

    • 如果不调用,getline 会立即读取到空行

  2. getline(cin, name)

    • 读取从当前光标到换行符之前的所有字符

    • 包含空格

    • 丢弃最后的换行符(不存入字符串)


五、关系比较运算符

string 类重载了完整的关系运算符,支持多种比较操作。

bool operator==(const string& lhs, const string& rhs);
bool operator!=(const string& lhs, const string& rhs);
bool operator<(const string& lhs, const string& rhs);
bool operator<=(const string& lhs, const string& rhs);
bool operator>(const string& lhs, const string& rhs);
bool operator>=(const string& lhs, const string& rhs);

比较规则:

  1. 按字典序逐个比较字符的ASCII码值

  2. 比较区分大小写

  3. 较短的字符串如果与较长字符串的前面部分相同,则认为较短字符串较小

示例代码:

#include <iostream>
#include <string>
using namespace std;int main() {string s1("apple");string s2("banana");string s3("Apple");string s4("app");// 1. 相等比较cout << boolalpha;cout << (s1 == "apple") << endl;    // 输出: truecout << (s1 == s3) << endl;         // 输出: false// 2. 不等比较cout << (s1 != s2) << endl;         // 输出: true// 3. 小于比较cout << (s1 < s2) << endl;          // 输出: true ('a' < 'b')cout << (s1 < s3) << endl;          // 输出: false ('a' > 'A')cout << (s4 < s1) << endl;          // 输出: true ("app" < "apple")// 4. 其他比较cout << (s1 <= s2) << endl;         // 输出: truecout << (s1 > s3) << endl;          // 输出: truecout << (s1 >= "apple") << endl;    // 输出: truereturn 0;
}

boolalpha 的基本作用

功能:将布尔值的输出从 0/1 格式转换为 true/false 文本格式

默认情况(不使用 boolalpha):

bool b = true;
cout << b;  // 输出: 1

使用 boolalpha 后

cout << boolalpha;
bool b = true;
cout << b;  // 输出: true


六、总结表

运算符功能描述支持的操作类型
=赋值string, const char*, char, initializer_list
+=追加string, const char*, char, initializer_list
+连接string + string, string + const char, const char + string, string + char, char + string
>> <<流操作输入输出流
== !=相等比较string与string, string与const char*
< <= > >=关系比较string与string, string与const char*
[]下标访问非const和const版本
bool空值检查隐式转换为bool

这些运算符重载使得string类的使用更加直观和方便,大大简化了字符串操作的代码编写。

http://www.dtcms.com/a/327325.html

相关文章:

  • LeetCode Day5 -- 栈、队列、堆
  • JavaScript 实现模块懒加载的几种方式
  • 如何轻松解除Facebook封锁
  • flinksql bug: Received resultset tuples, but no field str
  • 阿里云国际DDoS高防:添加网站配置指南
  • 腾讯codebuddy.ai 安装实测【从零开始开发在线五子棋游戏:完整开发记录】
  • 机械学习--TF-IDF实战--红楼梦数据处理
  • wordpress数据库导入时的#1044错误
  • Linux中使用计划任务和tar命令实现文件备份
  • 【Unity】Spine重新播放动画时会闪烁上次动画的残影
  • K8S 节点初始化一键脚本(禁用 SELinux + 关闭 swap + 开启 ipvs 亲测实用)
  • SQL 与 NoSQL 的核心区别
  • 部署高可用5节点 k8s 集群(v1.25.0版本)
  • Python中的高阶函数
  • vue+Django农产品推荐与价格预测系统、双推荐+机器学习预测+知识图谱
  • 六、SpringBoot多环境开发
  • 【Unity笔记】视频播放控制器全攻略:支持延迟播放、事件回调与多视频管理的完整实现
  • Linux 系统下 VS Code 降级至 1.85 版本教程:通过历史版本网站解决兼容性问题
  • 二叉树(七)--完全二叉树的节点个数
  • Day13 Vue工程化
  • mysql 简单操作手册
  • 行业分享丨SimSolid 在汽车零部件开发中应用的可行性调研及实践
  • 鸿蒙har包打包与引用,其它主工程entry引用本地har
  • Wireshark专家模式定位网络故障:14种TCP异常深度解剖
  • 西门子S7-200与S7-1200通过PPI以太网模块通讯,赋能汽车制造行业发展
  • 人机交互:连接人类与数字世界的桥梁
  • 【k8s】pvc 配置的两种方式volumeClaimTemplates 和 PersistentVolumeClaim
  • 计算机网络1-8:第一章 概述 习题课
  • UserController类讲解
  • Git 撤回已推送到远程的最近push