string类的实现(构造函数,析构函数,运算符重载)

String类的代码:

class String
{
public:
	String(char* str="")
	{
		_str = new char[strlen(str) + 1];
		strcpy(_str, str);
	}

	String(const String& str)
	{
		_str = new char[strlen(str._str) + 1];
		strcpy(_str, str._str);
	}

	~String()
	{
		delete[] _str;
	}

	String& operator=(const String& str)
	{
		if (&str == this)
			return *this;

		delete[] _str;

		_str = new char[strlen(str._str) + 1];
		strcpy(_str, str._str);

		return *this;
	}

	bool operator==(const String& str)
	{
		return strcmp(_str, str._str) == 0;
	}

	friend ostream& operator<<(ostream& o,String& str)
	{
		o << str._str;
		return o;
	}
private:
	char* _str;
};

包括构造函数,拷贝构造函数,析构函数,算数运算符重载。


下面是测试代码:

        String s1 = "hello";
	String s2 = "world";
	String s3 = "o";

	cout << "s1=" << s1 << endl;
	cout << "s2=" << s2 << endl;
	cout << "s3=" << s3 << endl;
	cout << endl;

	String s4(s1);
	String s5(s1);
	String s6(s1);

	s5 = s2;
	cout << "s4=" << s4 << endl;
	cout << "s5=" << s5 << endl;
	cout << (s4 == s5) << endl;
	cout << (s4 == s6) << endl;


测试结果:

wKioL1cJuujhZEhLAAAEkgO1ngA196.png

本文出自 “刘子蛋好好学习” 博客,转载请与作者联系!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值