欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > 关于string类的构造函数

关于string类的构造函数

2025/5/6 12:39:01 来源:https://blog.csdn.net/qq_55841287/article/details/147720307  浏览:    关键词:关于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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词