【C++】String类的非成员函数
📌string类的非成员函数
非成员函数重载共有6个,如下:
编辑
常用的非成员函数
函数名称 |
功能说明 |
|
operator+ |
尽量少用,因为传值返回,导致深拷贝效率低 |
|
operator>> |
输入运算符重载 |
|
operator<< |
输出运算符重载 |
|
getline |
获取一行字符串 |
|
relational operators |
大小比较 |
🎏operator+()函数
operator+()函数定义:编辑
使用operator+()函数完成string类对象和常量字符串相加:
int main()
{
string st1("Hello ");
string st2 = st1 + "world";
cout << st2 << endl;
return 0;
}
operator+()函数效果如下:编辑
🎏operator>>()函数
operator>>()函数定义:
编辑
使用operator>>()函数从流中提取字符串:
int main()
{
string st1;
cin >> st1;
cout << st1 << endl;
return 0;
}
operator>>()函数效果如下:编辑
🎏operator<<()函数
operator<<()函数定义:
编辑
使用operator<<()函数在string类对象后追加内容:
int main()
{
string st1("hello!");
cout << st1;
return 0;
}
operator<<()函数效果如下:编辑
🎏getline()函数
getline()函数定义:
编辑
使用getline()函数将行从流中获取到字符串:
int main()
{
string st1;
std::getline(cin,st1);
cout << st1 << endl;
return 0;
}
getline()函数效果如下:(使用getline流插入字符时可以无视空格,直到遇到回车才截止)编辑
🎏relational operators
relational operators定义:
编辑
使用relational operators比较字符串:
int main()
{
string st1("hello");
string st2("world");
cout << (st1 > st2) << endl;
cout << (st1 >= st2) << endl;
cout << (st1 == st2) << endl;
cout << (st1 != st2) << endl;
cout << (st1 <= st2) << endl;
cout << (st1 < st2) << endl;
return 0;
}
relational operators效果如下:编辑
结语
希望这篇关于C++string类的博客能对大家有所帮助,欢迎大佬们留言或私信与我交流.
学海漫浩浩,我亦苦作舟!关注我,大家一起学习,一起进步!
- 点赞
- 收藏
- 关注作者
评论(0)