C++:STL string(一)

本次编译环境为vs2022

文章目录


前言

我们了解完STL后 开始初步学习 STL里面的string类的内容

一.标准库中的string类

https://cplusplus.com/reference/string/string/?kw=string

这个网址可以看到string类里的内容

1.auto 范围for

在早期C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量,后来这个不重要了。C++11中,标准委员会变废为宝赋予了auto全新的含义即:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得。

用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量。

auto不能作为函数的参数,可以做返回值,但是建议谨慎使用

auto不能直接用来声明数组

通过代码简单了解

cpp 复制代码
int main()
{
	int arr[] = { 1,2,3,4,5 };
	for (auto& e : arr)
		e *= 2;
	for (auto e : arr)
		cout << e << " " << endl;

	string str("hello world");
	for (auto ch : str)
	{
		cout << ch << " ";
	}
	cout << endl;
	return 0;
}

输出是这样的

二.string类的模拟实现

cpp 复制代码
class string
{
public:
	string(const char* str)
	{
		if (nullptr == str)
		{
			return;
		}
		_str = new char[strlen(str) + 1];
		strcpy(_str, str);
	}
	string(const string& s)
		:_str(nullptr)
	{
		string tmp(s._str);
		swap(_str, tmp._str);
	}
	string& operator=(string s)
	{
		swap(_str, s._str);
		return *this;
	}
	~string()
	{
		if (_str)
		{
			delete[] _str;
			_str = nullptr;
		}
	}
private:
	char* _str;
};

最简单的string类的书写

赋值 构造 析构等

总结

简单的了解了一下string的内容 明天我们将扩展string类并给出完整且流利的讲解!

相关推荐
樱木Plus1 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit3 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_4 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星4 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛6 天前
delete又未完全delete
c++
端平入洛7 天前
auto有时不auto
c++
郑州光合科技余经理8 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1238 天前
matlab画图工具
开发语言·matlab
dustcell.8 天前
haproxy七层代理
java·开发语言·前端
norlan_jame8 天前
C-PHY与D-PHY差异
c语言·开发语言