string的构造和opertor=函数_C++

博客主要围绕string的构造函数展开,提及了string函数的初始化,还介绍了string的opertor=函数,同时指出string的析构函数无需手动调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

string的构造函数

string函数的初始化

/*
>Plan:string的初始化
>Author:ADiiana
>Time:2019/03/17
*/

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

int main(){
	std::string s0("Initial string");

	// constructors used in the same order as described above:
	string s1;
	string s2(s0);
	string s3(s0, 8, 3);	//从s0的第8个字符开始,取3个字符构造s3
	string s4("A character sequence");	
	string s5("Another character sequence", 12);	//取该字符串的12个字符构造s5
	string s6a(10, 'x');	//将s6a初始化为10个x
	string s6b(10, 42);      // 42 is the ASCII code for '*',同上
	string s7(s0.begin(), s0.begin() + 7);		//从s0的第1个字符开始,取7个字符构造s7
	string s8[] = { "hello123", "world" };		//初始化一个string数组,这个数组的每一个元素都是string对象

	cout << "s1: " << s1 << endl;
	cout << "s2: " << s2 << endl;
	cout << "s3: " << s3 << endl;
	cout << "s4: " << s4 << endl;
	cout << "s5: " << s5 << endl;
	cout << "s6a: " << s6a << endl;
	cout << "s6b: " << s6b << endl;
	cout << "s7: " << s7 << endl;
	cout << "s8: " << s8[0] << " " << s8[1] << endl;
	//cout << s8[1].size() << endl;

	system("pause");
	return 0;
}

输出:

在这里插入图片描述
string的析构函数不需要我们调用

string的opertor=函数

/*
>Plan:string的opetor=
>Author:ADiiana
>Time:2019/03/17
*/

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

int main(){

	string str1, str2, str3;
	str1 = "Test string: ";   // c-string
	str2 = 'x';               // single character
	str3 = str1 + str2;       // string

	//string str4 = 'x';		//编译错误,不能用char类型初始化string,只能赋值。
	string str5 = "hello world";	//正确
	
	cout << str3 << endl;
	cout << str5 << endl;
	system("pause");
	return 0;
}

输出:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值