C++中String类的实现

要注意字符串是否为空

代码实现:

#include <iostream>
using namespace std;

#include <string.h> 

class CString
{
public:
	CString(char* p = "")//构造函数 
	{
		mstr = new char[strlen(p) + 1]();
		strcpy(mstr, p);
	}
	CString(const CString& rhs)//拷贝构造函数 
	{
		mstr = new char[strlen(rhs.mstr) + 1]();
		strcpy(mstr, rhs.mstr);
	}
	~CString()//析构函数 
	{
		delete mstr;
		mstr = NULL;
	}
	CString& operator=(const CString& rhs)//赋值运算符的重载函数 
	{
		if (this != &rhs)
		{
			delete mstr;
			mstr = new char[strlen(rhs.mstr) + 1];
			strcpy(mstr, rhs.mstr);
		}
		return *this;
	}
	bool operator !=(const CString& rhs)//重载!= 
	{
		return strcmp(mstr, rhs.mstr) != 0;
	}
	bool operator ==(const CString& rhs)//重载== 
	{
		return !(*this != rhs);
	}
	
private:
	char* mstr;
	friend istream& operator >>(istream&, CString&);//重载输入流运算符 
	friend const CString operator+(const CString&, const CString&);//重载+ 
	friend ostream& operator<<(ostream&, const CString&);//重载输出流运算符 
}; 

//类外实现重载输入流运算符 
istream& operator >>(istream& in, CString& rhs)
{
	char *p = new  char[100]();
	in >> p;
	int i = 0;
	if (p[99] == '0')
	{
		i = strlen(p);
	}
	else
	{
		i = 100;
	}
	delete rhs.mstr;
	rhs.mstr = new char[i + 1]();
	strcpy(rhs.mstr, p);
	return in;
}

//类外实现重载+ 
const CString operator+(const CString& lhs, const CString& rhs)
{
	char* tmp = new char[strlen(lhs.mstr) + strlen(rhs.mstr) + 1]();
	strcat(tmp, lhs.mstr);
	strcat(tmp, rhs.mstr);
	return CString(tmp);
}

//类外实现重载输出流运算符 
ostream& operator<<(ostream& out, const CString& rhs)
{
	out << rhs.mstr << " ";
	return out;
}

int main()
{
	CString str1;
	CString str2("hello");
	CString str3(str2);
	cout << "str1:"; 
	cin >> str1;
	str3 = "hello";
	str3 = str3 + "world";
	cout << "str2:" << str2 << endl;
	cout <<"str3:" << str3 << endl;

	return 0;
}


string类是C++中很重要的类 一定要掌握 面试的时候会问到


运行结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值