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

String类的代码:

创新互联自2013年创立以来,先为三台等服务建站,三台等地企业,进行企业商务咨询服务。为三台企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

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;

测试结果:

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


文章标题:string类的实现(构造函数,析构函数,运算符重载)
标题来源:http://csruizhi.cn/article/jpidjh.html

其他资讯

Copyright © 2007-2024 成都优众联杰科技有限公司 All Rights Reserved 蜀ICP备2024116266号
友情链接: 成都网站建设 移动网站建设 高端网站设计推广 企业网站设计 品牌网站建设 成都网站建设 成都网站建设 成都定制网站建设 成都网站建设 成都定制网站建设 营销网站建设 H5网站制作 成都网站建设 成都网站设计 网站制作 手机网站制作 网站建设方案 成都网站建设 泸州网站建设 营销网站建设 成都网站建设 成都网站建设公司