前面通过前面篇文章介绍了
中的各项基本知识。从本篇文章开始,将对
中的
中的各项内容进行介绍:
目录
1.
string类对象的常见构造:
首先,对于的使用,需要引入头文件:
#include<string>
对于类中的常见构造,可以通过string::string - C++ Reference (cplusplus.com)进行查询。具体如下:
文章将对上述图片中某几个常用的函数进行介绍,其他函数的使用方法可以通过上方网址进行查阅。对于上述函数的作用,主要是用于创建一个类对象。例如,创建一个空的
类对象的方法为:
int main()
{
string s1; //创建一个空的string类对象
return 0;
}
如果想创建一个包含内容的类对象,其方法为:
string s2("hello world");
上述方法是使用了一个常量字符串来初始化这个类对象。对应了上图中给出的:
string(const char* str)
在上图中,有一个函数中的参数包含了引用,即:
string( const char& str)
此函数的功能可以理解为一个拷贝构造函数,使用方法有如下两种:
string s3 = s2;
string s4(const char& s2);
对于类对象的打印,直接使用
即可,例如:
int main()
{
string s1; //创建一个空的string类对象
string s2("hello world");
string s3 = s2;
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
return 0;
}
2. string类对象的赋值操作:
对于类对象的赋值操作,可以分为三类:
string& operator= (const string& str);
string& operator= (const char* s);
string& operator= (char c);
对于上面三类赋值操作的使用,如下所示:
s1 = s2;
cout << s1 << endl;
s1 = 'x';
cout << s1 << endl;
s1 = "hello worle";
cout << s1 << endl;
运行结果如下:
3. string类对象的访问与遍历:
3.1 string类对象的访问:
对于类对象的访问,通过
来实现。对于此函数,主要有两种形式:
char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
对于二者的不同点,可以认为第一种可读可写,但是第二种只能读。例如,访问上述代码中,中下标为