Cpp::STL—string类的使用与理解(上)(8)-一、string类对象的构造函数

时间:2024-10-05 07:41:44

在这里插入图片描述

  事先声明,就像我前言说的一样,string设置的很冗余,所以我挑选几个常见的来讲,甚至于有几个我挑出来的也不多见,下文同理

(constructor)函数名称 功能说明
string() (重点) 默认构造,创建一个空串,这个空串的长度是0
string(const char* s) (重点) 用C-string来构造string类对象
string(size_t n, char c) 通过一个字符来构造,一个字符重复n次
string(const string& s) (重点) 拷贝构造函数
string(const string& str,size_t pos,size_t len = npos)(重点) 从str中pos指向位置先后拷贝len长度字符,两种情况下文给出

string()

功能:构造空string类对象,其长度为0

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s1;
	cout<<s1.length()<<endl; // 0

	return 0;
}

string(const char* s)

功能:使用C-string构造string类对象。在非空字符串中,从s指向位置拷贝一份字符串

#include<iostream>
#include<string>
using namespace std;

int main()
{
	// 相当简便
	string s1("Hello,world!");
	cout << s1 << endl; // Hello,world!

	// 其实我们还有一种清晰明了的方法
	const char* s = "Hello,world!";
	string s2(s);
	cout << s2 << endl; // Hello,world!

	return 0;
}

string(size_t n, char c)

功能:通过一个字符来构造,一个字符重复n次

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s1(5,'r');
	cout << s1 << endl; // rrrrr

	return 0;
}

string(const string& s)

功能:拷贝构造,通过已有对象拷贝构造一个新的对象,这个对象和已有对象在逻辑上是相同的

#include<iostream>
#include<string>
using namespace std;

int main()
{
	// 这两种都称为拷贝构造
	string s1("Hello,world!");
	string s2(s1);
	string s3 = s1;

	return 0;
}

string(const string& str,size_t pos,size_t len = npos)

功能:从str中pos指向位置先后拷贝len长度字符。出现两种结果:拷贝到str最后一个字符或没有达到最后一个字符完成拷贝

  第三个参数len类型为 size_t ,而缺省值 npos == -1 导致了 npos 按补码形式是32个比特位1,而又被当作正数还原为原码,就是 INT_MAX(涉及到编码那块,考验你前面学得扎不扎实的时候到了)。所以对于当没有明确 len 数值,默认是从 pos 位置拷贝字符串到最后一个字符,而如果str已经拷贝到最后一个字符了,那就结束拷贝

这是原文翻译,你英语好的话你自己翻译~
Copies the portion of str that begins at the character position pos and spans len characters (or until the end of str, if either str is too short or if len is string::npos).

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s1("Hello,world!");
	string s2(s1,2,3);
	cout << s2 << endl;

	return 0;
}