关于string类的构造函数
一、string(const char* s, size_type n, const Allocator & a=Allocator());
这个构造函数接受一个C风格字符串,并指定复制这个C风格字符串的n个字符作为该string对象的内部数据成员;
这里就是需要注意一下,当n大于s的长度的时候,string对象会继续获取s后面的内存区域的值,所以这里调用该string的size()方法的时候会返回n;
二、string(const string & st, size_type pos, size_type n, const Allocator & a=Allocator());
这个构造函数接收一个string对象的引用,为了方便起见,这里将pos参数设置为0,如果n大于st的长度的时候,string对象只会获取到st长度的数据,不会继续往后面的内存区获取数据,所以该string对象的size()方法返回n和st.size()较小的那个;
代码:
#include <iostream>
#include <string>int main()
{using namespace std;string s1("manba");string s2("manba", 100);string s3(s1, 0, 100);cout << "size of s1: " << s1.size() << endl;cout << "size of s2: " << s2.size() << endl;cout << "size of s3: " << s3.size() << endl;return 0;
}
结果:
size of s1: 5
size of s2: 100
size of s3: 5