字符串类——MyString类

字符串操作,写了一个自己的string类,小小的练习。

#pragma once
#include <iostream>
#include <cstring>

class MyString {
public:
	MyString(); //默认构造函数
	MyString(const char* s); //构造函数
	MyString(const MyString& s); //拷贝构造函数
	~MyString(); // 析构函数
	MyString& operator=(const MyString& s); // 赋值函数
	MyString& operator+(const MyString& s); // +符号重载
private:
	int m_size;
	char* m_data;
};

MyString::MyString() {
	m_size = 0;
	m_data = new char[1];
	m_data[0] = '\0';
	std::cout << "默认构造函数 " << "m_size:" << m_size;
	std::cout << ",data:" << m_data << std::endl;
}

MyString::MyString(const char* s) {
	if (s == nullptr) {
		m_size = 0;
		m_data = new char[1];
		m_data[0] = '\0';
	}
	else {
		m_size = strlen(s);
		m_data = new char[m_size + 1];
		strcpy(m_data, s);
	}
	std::cout << "常规构造函数 " << "m_size:" << m_size ;
	std::cout << ",data:" << m_data << std::endl;
}

MyString::MyString(const MyString& s) {
	m_size = s.m_size;
	m_data = new char[m_size + 1];
	strcpy(m_data, s.m_data);
	std::cout << "拷贝构造函数 " << "m_size:" << m_size;
	std::cout << ",data:" << m_data << std::endl;
}

MyString::~MyString() {
	delete[] m_data;
}

MyString& MyString::operator=(const MyString& s) {
	if (&s == this)
		return *this;
	delete[] m_data;
	m_size = strlen(s.m_data);
	m_data = new char[m_size + 1];
	strcpy(m_data, s.m_data);

	std::cout << "赋值函数 " << "m_size:" << m_size;
	std::cout << ",data:" << m_data << std::endl;
	return *this;
}

MyString& MyString::operator+(const MyString& s) {
	int l_size = m_size + s.m_size;
	char* l_data = new char[l_size + 1];
	strcpy(l_data, m_data);
	strcpy(l_data + m_size, s.m_data);
	delete[] m_data;
	m_size = l_size;
	m_data = l_data;
	std::cout << "字符串加法函数 " << "m_size:" << m_size ;
	std::cout << ",data:" << m_data << std::endl;

	return *this;
}

main函数类调用MyString。

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

using namespace std;

int main(int argc, char* argv[]) {

	MyString ms;
	MyString ms1("hello world!");
	MyString ms2=ms1; // 等效为 ms2(ms1)调用拷贝构造函数
	MyString ms3(ms1);
	ms3 = ms2 + ms1;

}

输出结果为;

  • 0
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值