自己写一个string类


class my_string {
	friend std::ostream& operator<<(ostream& os, const my_string& str);
	friend std::istream& operator >>(istream& is, my_string& str);
public:
	my_string(const char * str = NULL);
	my_string(const my_string &);
	~my_string();
	my_string operator=(const my_string &);
	my_string operator+(const my_string &);
	bool operator==(const my_string&);
	char& operator[](int);
	int size() { return strlen(this->data) + 1; }
private:
	char* data;
};

my_string::my_string(const char* str)
{
	if (str == NULL)this->data = NULL;
	else
	{
		this->data = new char[strlen(str) + 1];
		strcpy(data,str);
	}
	
}

my_string::my_string(const my_string& other)
{
	if (other.data == NULL)this->data = NULL;
	else
	{
		this->data = new char[strlen(other.data)+1];
		strcpy(this->data,other.data);
	}
}

my_string::~my_string()
{
	delete[] this->data;
}

my_string my_string::operator=(const my_string& other)
{
	delete[] this->data;
	if (other.data == NULL)this->data = NULL;
	else
	{
		this->data = new char[strlen(other.data)+1];
		strcpy(this->data,other.data);
	}
	return *this;
}

my_string my_string::operator+(const my_string& other)
{
	if (other.data == NULL)return *this;
	else if(this->data == NULL)
	{
		this->data = new char[strlen(other.data) + 1];
		strcpy(this->data, other.data);
		return *this;
	}
	else
	{
		my_string strTmp;
		strTmp.data = new char[strlen(this->data) + strlen(other.data) + 1];
		strcpy(strTmp.data, this->data);
		strcat(strTmp.data, other.data);
		return strTmp;
	}
}

bool my_string::operator==(const my_string& other)
{
	int tmp = 0;
	tmp = strcmp(this->data,other.data);
	if (tmp == 0)return 1;
	else return 0;
}

char& my_string::operator[](int index)
{
	return this->data[index];
}

ostream& operator<<(ostream& os, const my_string& str)
{
	os << str.data;
	return os;
}

istream& operator>>(istream& is, my_string& str)
{
	char buffer[4096];
	is >> buffer;
	str.data = buffer;
	return is;
}

int main()
{
	my_vector<int> mv1(3);

	mv1[0] = 0;
	mv1[1] = 1;
	mv1[2] = 2;

	my_vector<int> mv2(mv1);

	cout << mv2[0] << mv2[1] << mv2[2] << endl;

	my_string str1, str2,str3;
	str1 = "qweewq";
	str2 = "qweewq";
	str3 = str1 + str2;
	cout << str3 << endl;
	if (str1 == str2)cout << "str1 和 str2 相同 " << endl;
	cout << str1[1] << str1.size() << endl;

	return 0;
}

 

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值