类string运算符的重载

本文介绍了如何在 C++ 中实现一个简单的 String 类,并重载了 +、==、!=、> 和 < 运算符,允许字符串间的拼接及比较操作。此外还展示了如何通过重载流插入运算符来打印 String 对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于昨天写的Int运算符的重载,今天又完善了一下Stringl类的运算符重载。代码如下:
#include<iostream>
using namespace std;


class String;
ostream& operator<<(ostream &out,const String &s);

class String
{
	friend ostream& operator<<(ostream &out,const String &s);
public:
	String(const char *str)   //普通构造函数
	{
		m_data = new char[strlen(str)+1];
		strcpy(m_data,str);
	}

	String(const String &s)   //拷贝构造函数
	{
		m_data = new char[strlen(s.m_data) +1];
		strcpy(m_data,s.m_data);
	}
	~String()
	{
		delete []m_data;
	}

	String& operator=(const String &s)
	{
		if ( this != &s)
		{
			delete[]m_data;
			m_data = new char[strlen(s.m_data) +1];
			strcpy(m_data,s.m_data);
		}
		return *this;
	}
public:
	String operator+(const String &s)
	{
		char *p = new char[strlen(m_data) +strlen(s.m_data)+1];
		strcpy(p,m_data);
		strcat(p,s.m_data);

		String tmp(p);
		delete []p;
		return tmp;
	}
	//////////////////////////////////////////////////
	bool operator==(const String &s)
	{
		if (strcmp(m_data,s.m_data) == 0)
			return true;
		else
			return false;
	}
	bool operator!=(const String &s)
	{
		if (strcmp(m_data,s.m_data) != 0)
			return true;
		else 
			return false;
	}
	bool operator>(const String &s)
	{
		if (strcmp(m_data,s.m_data) > 0)
			return true;
		else
			return false;
	}
	bool operator<(const String &s)
	{
		if (strcmp(m_data,s.m_data) < 0)
			return true;
		else
			return false;
	}

	///////////////////////////////////////
private:
char *m_data;
};

ostream& operator<<(ostream &out,const String &s)
{
	out<<s.m_data;
	return out;
}
void main()
{
	String s1("hello");
	String s2("world");
    String s3= s1 + s2;
	cout<<s1<<endl;
	cout<<s3<<endl;

	String s4("hello,world");
	String s5("hello,world");
	String s6("hello"); 

	if (s4 == s5)
	{
		cout<<"s4和s5相等!"<<endl;
	}
	else
	{
		cout<<"s4和s5不相等!"<<endl;
	}
	if(s4 > s6)
	{
		cout<<"s4大于s6!"<<endl;
	}

	else if(s4 < s6)
	{
		cout<<"s4小于s6!"<<endl;
	}
	else 
	{
		cout<<"s4等于s6"<<endl;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值