自己写一个string类

本文介绍了一个使用C++实现的自定义字符串类,包括构造函数、析构函数、运算符重载等关键部分。该类支持字符串连接操作,并通过深拷贝避免内存泄漏。

头文件:

#ifndef _STRINGS_
#define _STRINGS_
#include <iostream>
using namespace std;

class Strings
{
	friend ostream& operator<<(ostream& os, const Strings& s);
public:
	Strings();
	Strings(char *s);
	Strings(const Strings &s);
	Strings& operator = (const Strings& s);
	Strings& operator + (const Strings& s);
	Strings& operator + (const char *s);
	~Strings(){
		if(str != NULL)
			delete [] str;
		cout<<"~Strings() is called"<<endl;
	}
	void display();

private:
	char *str;
};

#endif
源文件:

#include "strings.h"
#include <cstring>
#include <iostream>
using namespace std;

ostream& operator<<(ostream& os, const Strings& s)
{
	cout<<s.str;
	return os;
}

Strings::Strings()
{
	str = new char('A');
	cout<<"Strings (char *s) is called"<<endl;
}

Strings::Strings(char *s){
	str = new char[strlen(s)+1];
	if (str)
	{
		strcpy(str, s);
	}
	cout<<"Strings(char *s) is called"<<endl;
}

Strings::Strings(const Strings &s){
	str = new char[strlen(s.str)+1];
	if(str){
		strcpy(str, s.str);
	}
	cout<<"Strings(const Strings &s) is called"<<endl;
}

Strings& Strings::operator =(const Strings &s)
{
	if(this != &s){
		if (str != NULL)
		{
			delete [] str;    //防止内存泄露
		}
		str = new char[strlen(s.str)+1];
		strcpy(str, s.str);
		cout<<"Strings(const Strings &s) is called"<<endl;
	}
	return *this;
}

Strings& Strings::operator +(const Strings& s)
{
	char *temp;
	temp = new char[strlen(str)+strlen(s.str)+1];
	strcpy(temp, str);
	delete [] str;
	strcat(temp, s.str);
	str = temp;
	return *this;
}

Strings& Strings::operator + (const char *s)
{
	char *temp;
	temp = new char[strlen(str)+strlen(s)+1];
	strcpy(temp, str);
	delete [] str;
	strcat(temp, s);
	str = temp;
	return *this;
}

void Strings::display() {
	char *p = str;
	while (*p != '\0')
	{
		cout<<*p;
		p++;
	}
	cout<<endl;
	cout<<"display is called"<<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值