string 构造函数

本文介绍了C++11中新增的移动构造函数,它在创建string对象时提供了一种优化性能的方式,不同于复制构造函数。虽然在处理char*时可能用处有限,但移动构造函数对于提升代码效率有重要意义。

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

代码

#include <iostream>
#include <string>

//string构造函数

int main() {
	using namespace std;

	//NBTS 表示以空字符串结束的字符串
	//ctor 表示构造函数

	//构造函数:str(const char*s)  将string对象初始化为s指向的NBTS
	string one("Lottery Winner!");     // ctor #1
	cout << one << endl;               // overloaded <<

//----------------------------------------------------------

	//构造函数:str(size_type n ,char c) 创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c
	string two(20, '$');               // ctor #2
	cout << two << endl;

//----------------------------------------------------------

	//string(const string&str) 复制构造函数
	string three(one);                 // ctor #3
	cout << three << endl;

//----------------------------------------------------------
	one += " Oops!";                   // overloaded +=
	cout << one << endl;
	two = "Sorry! That was ";
	three[0] = 'P';
	string four;                       // ctor #4
	four = two + three;                // overloaded +, =
	cout << four << endl;
//----------------------------------------------------------
	
	//将string对象的初始化为s指向的NBTS的前n个字符,即使超过了NBTS结尾
	//string(const string& str ,string size_type)
	char alls[] = "All's well that ends well";
	string five(alls, 20);              // ctor #5
	cout << five << "!\n";

//----------------------------------------------------------
	//template<class Iter> 
	//string (Iter begin,Iter end)  //模板参数Iter
	string six(alls + 6, alls + 10);     // ctor #6
	cout << six << ", "; //alls 数组相当于指针,所以alls+6 类型是char*
//----------------------------------------------------------
	//string seven(five+6 , five+10) 不能,对象名(string) 不同于数组名,不会被看作是对象的地址,因此five不是指针。
	//five[6] 是一个char值,所以&five[6] 是一个地址。
	string seven(&five[6], &five[10]); // ctor #6 again
	cout << seven << "...\n";
//----------------------------------------------------------
	string eight(four, 7, 16);         // ctor #7
	//将一个string对象的部分内容复制到构造的对象中
	//从four的第8个字符(位置7)开始,将16个字符复制到eight中
	cout << eight << " in motion!" << endl;

	return 0;
}

//----------------------------------------------------------
//Lottery Winner!
//$$$$$$$$$$$$$$$$$$$$
//Lottery Winner!
//Lottery Winner!Oops!
//Sorry!That was Pottery Winner!
//All's well that ends!
//well, well...
//That was Pottery in motion!

c++11新增的构造函数

  • string(string && str)类似于复制函数,导致新创建的string为str的副本。但与复制构造函数不同的是,它不能保证将str视为const,称为移动构造函数
    • 编译器使用这个以优化性能。
  • stirng(initialize_list<char> il)
    • string pi = {'l','i','s'}
    • string pi { 'l' , 'i', 's'}
    • 这可能用处不大,因为使用char* 更容易
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值