C++中实现String类

news2024/10/5 13:42:37

String类实现

  • 概述
  • 示例
    • 开发环境
    • 代码
    • 运行结果
  • 注意

概述

本文主要记录自己实现一个String类中的部分功能。

示例

开发环境

Windows下Visual Studio 2019。

代码

MyString.h

#pragma once
#include <iostream>

class MyString{
public:
	MyString();
	MyString(char *p);
	MyString(const char *p);
	MyString(const MyString& s);
	MyString(MyString&& s);
	MyString& operator=(const MyString& s);
	MyString& operator=(MyString&& s);
	bool operator<(const MyString &s);
	bool operator==(const MyString& s);
	MyString& operator+=(const MyString& s);
	int getLeng()const;
	char getIndexCharacter(const int& index);
	friend std::ostream& operator<<(std::ostream & o,const MyString& s);//友元函数不是类成员函数,可访问私有成员
	friend std::istream& operator>>(std::istream& i,MyString &s);
private:
	char* m_pStr;
	int m_len;
};

MyString.cpp

#include "MyString.h"
#include <string>

MyString::MyString():m_pStr(nullptr),m_len(0)
{
	m_pStr = new char[1];
	m_pStr[0] = '\0';
	m_len = 1;
}

MyString::MyString(char* p)
{
	if (p) {
		int nLen = strlen(p);
		m_pStr = new char[nLen + 1];
		memset(m_pStr, 0, nLen + 1);
		strcpy_s(m_pStr, nLen + 1, p);//目标缓存区的大小
		m_len = nLen;
	}
	else {
		MyString();
	}
}

MyString::MyString(const char* p)
{
	if(p){
		int nLen = strlen(p);
		m_pStr = new char[nLen +1];
		memset(m_pStr,0,nLen+1);
		strcpy_s(m_pStr,nLen+1,p);//目标缓存区的大小
		m_len = nLen;
	}
	else {
		MyString();
	}
}

MyString::MyString(const MyString& s)
{
	m_len = s.m_len;
	m_pStr = new char[m_len+1];
	memset(m_pStr, 0, m_len + 1);
	strcpy_s(m_pStr,m_len+1 ,s.m_pStr);
	m_pStr[m_len] = '\0';
}

MyString::MyString(MyString&& s)
{
	m_len = s.m_len;
	m_pStr = s.m_pStr;
	s.m_pStr = nullptr;
	s.m_len = 0;
}

MyString& MyString::operator=(const MyString& s)
{
	// TODO: 在此处插入 return 语句
	if (this != &s) {
		m_len = s.m_len;
		m_pStr = new char[m_len +1];
		memset(m_pStr,0,m_len+1);
		strcpy_s(m_pStr,m_len+1,s.m_pStr);
		m_pStr[m_len] = '\0';
	}
	return *this;
}

MyString& MyString::operator=(MyString&& s)
{
	// TODO: 在此处插入 return 语句
	if (this != &s) {
		m_len = s.m_len;
		m_pStr = s.m_pStr;
		s.m_len = 0;
		s.m_pStr = nullptr;
	}
	return *this;
}

bool MyString::operator<(const MyString& s)
{
	if (strcmp(m_pStr,s.m_pStr) < 0) {
		return true;
	}
	return false;
}

bool MyString::operator==(const MyString& s)
{
	if (strcmp(m_pStr,s.m_pStr) == 0) {
		return true;
	}
	return false;
}

MyString& MyString::operator+=(const MyString& s)
{
	// TODO: 在此处插入 return 语句
	m_len += s.m_len;
	char* pTemp = m_pStr;
	m_pStr = new char[m_len+1];
	memset(m_pStr,0,m_len+1);
	strcpy_s(m_pStr,m_len+1,pTemp);
	strcat_s(m_pStr, m_len + 1, s.m_pStr);
	m_pStr[m_len] = '\0';

	return *this;
}

int MyString::getLeng() const
{
	return m_len;
}

char MyString::getIndexCharacter(const int& index)
{
	if (index >=0 && index < m_len) {
		return m_pStr[index];
	}
	return -1;
}

std::ostream& operator<<(std::ostream& o,const MyString& s)
{
	// TODO: 在此处插入 return 语句
	o << "字符串的长度:" << s.m_len << ",字符串:" << s.m_pStr;
	return o;
}

std::istream& operator>>(std::istream& i,MyString &s)
{
	// TODO: 在此处插入 return 语句
	i >> s.m_len >> s.m_pStr;
	return i;
}

main.cpp

#include <iostream>
#include "MyString.h"

using namespace std;


int main(int argc,char *argv[]) {
    MyString s;
    cout <<"字符串s: "<< s << endl;
    const char* p = "future";
    MyString s0(p);
    cout << "字符串s0: " << s0 << endl;
    MyString s1("hello");
    cout << "字符串s1: " << s1 << endl;
    
    char c[15] = "hello world";
    MyString s2(c);
    cout << "字符串S2:" << s2 << endl;
    MyString s3(s2);
    cout << "字符串s3:" << s3 << endl;
    MyString s4(move(s0));
    cout << "字符串s4:" << s4 << endl;
    MyString s5 = s1;
    cout << "字符串s5:" << s5 << endl;
    MyString s6 = move(s2);
    cout << "字符串s6:" << s6 << endl;
    if (s5 == s6) {
        cout << "s5与s6相等!" << endl;
    }
    else if(s5 <s6){
        cout << "s5与s6小于s6!" << endl;
    }
    else {
        cout << "s5与s6大于s6!" << endl;
    }
    s5 += s6;
    cout << "s5追加s6之后: " << s5 << endl;
    cout << "s5的长度:" <<s5.getLeng()<< endl;
    cout << "s5的第8个字符:" << s5.getIndexCharacter(11) << endl;
	return 0;
}

运行结果

在这里插入图片描述

注意

  • 上面的示例在实现时,输入输出运算符的重载时作为友元函数来声明的,需要访问类对象的成员变量,故而含有两个参数。
    一般输出、输出运算符重载都作为类的友元函数。
friend std::ostream& operator<<(std::ostream & o,const MyString& s);//友元函数不是类成员函数,可访问私有成员
friend std::istream& operator>>(std::istream& i,MyString &s);
  • 其中构造函数:
MyString(MyString&& s);

为移动拷贝构造函数。

  • 下面的赋值运算符重载:
MyString& operator=(MyString&& s);

为移动赋值运算符重载。
参数右值引用传参的时候,使用move()。 可看上述示例调用处。

  • 声明为移动构造函数和移动赋值运算符重载的好处 :
    避免了深拷贝,只转移所有权,移动之后(即转移所有权之后),原来的对象中的数据被清空,但对象依旧存在。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1511059.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

c语言函数:atoi与memset

1.atoi函数的头文件stdlib.h 空格跳过&#xff0c;遇到非数字非空格字符准备结束&#xff0c;如果前面有数字则输出数字&#xff0c;没有则输出0&#xff0c;其中-号不受影响&#xff0c;但不输出 memset函数&#xff08;目标值&#xff0c;操作值&#xff0c;字节数&#xff…

LeetCode102题:二叉树的层序遍历(python3)

代码思路&#xff1a;使用队列先进先出的特性&#xff0c;queue[]不为空进入for循环&#xff0c;tmp存储每层的节点&#xff0c;将结果添加至res[]中。 python中使用collections中的双端队列deque()&#xff0c;其popleft()方法可达到O(1)时间复杂度。 class Solution:def lev…

YOLOv9改进项目|关于本周更新计划的说明24/3/12

目前售价售价59.9&#xff0c;改进点30个 专栏地址&#xff1a; 专栏介绍&#xff1a;YOLOv9改进系列 | 包含深度学习最新创新&#xff0c;主力高效涨点&#xff01;&#xff01;&#xff01; 日期&#xff1a;24/3/12 本周更新计划说明&#xff1a; 1. 更新华为Gold YOLO中的…

为表重命名

oracle从入门到总裁:​​​​​​https://blog.csdn.net/weixin_67859959/article/details/135209645 为表重命名 DDL 属 于 数 据 对 象 定 义 语 言&#xff0c; 主 要 的 功 能 是 创 建 对 象&#xff0c; 所 以 表 创 建 单 词 是create 但问题是&#xff0c;这些对象被…

如何使用vue实现购物车中数字的增减操作

实现效果如下&#xff08;当点击购买数量的时候&#xff0c;可以增减&#xff09;&#xff1a; 首先&#xff0c;写出界面原型&#xff1a; <div id"container"><table ref"myTable"><thead></thead><tbody><tr><…

SQL数据库-SQL命令-SQL语言

我要成为嵌入式高手之3月12日Linux高编第二十天&#xff01;&#xff01; ———————————————————————————— 数据库软件 关系型数据库&#xff1a; Mysql Oracle SqlServer Sqlite 非关系型数据库&#xff08;相当于在内存中搞了一块空间&#xff…

Python 导入Excel三维坐标数据 生成三维曲面地形图(面) 2、线条平滑曲面但有间隔

环境和包: 环境 python:python-3.12.0-amd64包: matplotlib 3.8.2 pandas 2.1.4 openpyxl 3.1.2 scipy 1.12.0 代码: import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import griddata imp…

大模型时代下的 BI——智能问数

「智能问数」是 Sugar BI 基于文心大语言模型推出的对话式数据问答产品&#xff0c;让用户能够通过自然语言的方式进行对答形式的数据查询&#xff0c;系统自动使用可视化图表的方式呈现数据结果&#xff0c;并支持对数据做summary总结。 智能问数功能邀测中&#xff0c;欢迎CS…

海外媒体发稿:新闻媒体发稿7种方法-华媒舍

新闻报道媒体发稿营销推广是当代企业形象宣传的重要手段之一&#xff0c;合理推广可以提升品牌知名度、吸引住潜在用户。在这篇文章中&#xff0c;我们将要详细介绍七种科学合理的形式&#xff0c;帮助你完全把握新闻报道媒体发稿营销推广。 1.明确目标群体明确目标群体是实现推…

算法之滑动窗口

题目1:209. 长度最小的子数组 - 力扣&#xff08;LeetCode&#xff09; 解法⼀(暴力求解): 思路&#xff1a; 从前往后, 枚举数组中的任意⼀个元素, 把它当成起始位置, 然后从这个起始位置开始, 然 后寻找⼀段最短的区间, 使得这段区间的和「⼤于等于」⽬标值. 将所有元素作为…

郑州大学2024年3月招新赛题解

1.两重二for循环维护次大值 这里我就直接用map维护了&#xff0c;多了个logn复杂度还是可以的&#xff0c;下面是AC代码&#xff1a; #include<bits/stdc.h> using namespace std; int n,a[1010]; map<int,int> mp; int main(){cin>>n;int sum0;map<int,…

操作系统--LRU算法,手撕

今天研究一下LRU算法&#xff0c;上学期学数据结构的时候就应该学一下这个算法&#xff0c;不过后面操作系统也会讲到LRU算法 题目 LRU缓存leetocde146 LRU&#xff08;Least Recently Used&#xff0c;最近最少使用&#xff09;算法是一种常见的缓存替换算法&#xff0c;通…

索引失效的介绍和避免方法

索引是什么 在关系数据库 中&#xff0c;索引是一种单独的、物理的对数据库表中一列或多列的值进行排序的一种 存储结构 &#xff0c;它是某个表中一列或若干列值的集合和相应的指向表中物理标识这些值的数据页的逻辑指针清单。 索引的作用相当于图书的目录&#xff0c;可以根据…

​《宏伟世纪》在 TheSandbox 中带来虚拟苏丹体验!

《宏伟世纪》&#xff08;Magnificent Century&#xff09;与 The Sandbox 合作&#xff0c;将戏剧带入数字领域&#xff01;这部土耳其历史小说电视连续剧以苏丹苏莱曼大帝和许蕾姆苏丹的生平为原型&#xff0c;曾在 140 多个国家和地区播出&#xff0c;收视率超过 5 亿&#…

交换机STP工作原理

文章目录 一、确定交换机角色二、确定端口角色1.根端口选举2.指定端口选举3.非指定端口选举 三、确定端口状态常用查询命令实验拓扑实例一拓扑实例二拓扑实例三拓扑实例四拓扑图实例五 BPDU报文中携带的Root Identifier、Root Path Cost、Bridge Identifier、Port Identifier字…

13年老鸟整理,性能测试技术知识体系总结,从零开始打通...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 从个人的实践经验…

新质生产力浪潮下,RPA如何成为助力先锋?

新质生产力浪潮下&#xff0c;RPA如何成为助力先锋&#xff1f; 在数字化、智能化的今天&#xff0c;“新质生产力”一词越来越频繁地出现在我们的视野中。那么&#xff0c;究竟什么是新质生产力&#xff1f;它与我们又有什么关系&#xff1f;更重要的是&#xff0c;在这一浪潮…

2024年,10大产业趋势:创新驱动下的全面转型与发展

本趋势指南深入探讨塑造企业创新未来的力量&#xff0c;以及为什么企业必须改变创新方式。指南概述了创新未来的愿景&#xff0c;其中人类智慧和AI技术在创新中相结合&#xff0c;相互补充和放大&#xff0c;这将是一个全新范围的端到端创新平台&#xff0c;旨在将各个点连接起…

用chatgpt写论文重复率高吗?如何降低重复率?

ChatGPT写的论文重复率很低 ChatGPT写作是基于已有的语料库和文献进行训练的&#xff0c;因此在写作过程中会不可避免地引用或借鉴已有的研究成果和观点。同时&#xff0c;由于ChatGPT的表述方式和写作风格与人类存在一定的差异&#xff0c;也可能会导致论文与其他文章相似度高…

Python中Matplotlib保存图像时去除边框(坐标轴、白色边框、透明边框)方法

直接说解决方法&#xff1a; plt.savefig(‘image3.png’,bbox_inches‘tight’,pad_inches0) &#xff08;三行搞定&#xff09; import numpy as np import matplotlib.pyplot as pltimg np.random.randn(10,10)figplt.imshow(img) plt.axis(off) plt.savefig(image3.png,b…