c++实现MyString类

实现方法有构造函数,拷贝构造函数,移动构造函数。析构函数,字符串相加,字符串赋值,字符串移动赋值。判断两个 类是否相同,运算符[]重载,输出运算符重载

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<stdlib.h>

using namespace std;

class MyString {
public:
	char* str;
	MyString(const char* stra) :str(nullptr) {
		if (stra != nullptr) {
			size_t len = strlen(stra)+1;
			str = new char[len];
			strncpy(str, stra, len);
		}
		}
	MyString(const MyString& other) :str(nullptr) {
		 if(other.str!=nullptr){
			 size_t len = strlen(other.str)+1;
			 str = new char[len];
			 strncpy(str, other.str, len);
		}
	}
	MyString(MyString&& other) :str(nullptr) {
		str  = other.str;
		other.str = nullptr;
	}
	~MyString() {
		delete[] str;
	}
	MyString operator+(const MyString& other) {
		if (other.str != nullptr) {
			MyString result(*this);
			size_t len1 = strlen(str);
			size_t len2 = strlen(other.str);
			size_t len = len1 + len2 + 1;
			delete[] result.str;
			result.str = new char[len];
			strcpy(result.str, "");
			strcat(result.str, str);
			strcat(result.str, other.str);
			return result;
		}
		return *this;
	}
	MyString& operator=(const MyString& other) {
		if (this != &other) {
			delete[]this->str;
			if (other.str != nullptr) {
				size_t len = strlen(other.str) + 1;
				str = new char[len];
				strncpy(str, other.str, len );
			}
		}
		return *this;
	}
	MyString& operator=(MyString&& other) {
		if (this != &other) {
			delete[]this->str;
			str = other.str;
			other.str = nullptr;
		}
		return *this;
	}
	bool operator==(const MyString& other) const {
		return (strcmp(str, other.str) == 0);
	}

	bool operator!=(const MyString& other) const {
		return !(*this == other);
	}
	char& operator[](size_t index) {
		return str[index];
	}
	friend std::ostream& operator<<(std::ostream& os, const MyString& myStr);
};

std::ostream& operator<<(std::ostream& os, const MyString& myStr) {
	

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值