c++学习-oop-重载自增自减操作符

/*
	Date: 12/03/21 19:55
	Description: 重载自增自减操作符
		自增、自减操作符
		++	--
	重载前缀形式、后缀形式的自增自减操作符
		operator++();
		operator++(int); 
*/
#include<iostream>
#include<cstring>
using namespace std;

class String
{
public:
	String(char const *chars = "");
	String(String const &str);
	~String();
	
	void display()const;
	
	String &operator++();//前加加
	String const operator++(int);//后加加 
	
	String &operator--();//前加加
	String const operator--(int);//后加加 
private:
	char *ptrChars;
};

String &String::operator++()//前加加
{
	for(size_t i=0;i<strlen(ptrChars);++i)
	{
		++ptrChars[i];
	}
	return *this;
}

String const String::operator++(int)//后加加
{
	String copy(*this);
	++(*this);
	return copy;
}

String &String::operator--()
{
	for(size_t i=0;i<strlen(ptrChars);++i)
	{
		--ptrChars[i];
	}
	return *this;
}

String const String::operator--(int)
{
	String copy(*this);
	--(*this);
	return copy;
}



String::String(char const *chars)
{
	chars = chars ? chars :"";
	ptrChars = new char[strlen(chars)+1];
	strcpy(ptrChars,chars); 
}

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

String::~String()
{
	delete[] ptrChars; 
}

void String::display()const
{
	cout<<ptrChars<<endl;
}

int main()
{
	String s("ABC");
	s.display();
	
	++s;
	s.display();
	
	s++;
	s.display();
	
//	cout<<endl<<"new test"<<endl;
//	
//	String str1("ABC");
//	String str2(++str1);
//	String str3(str1++);
//	str1.display();
//	str2.display();
//	str3.display();
	
	cout<<endl<<"new test"<<endl;
	
	String str1("ABC");
	String str2(--str1);
	String str3(str1--);
	str1.display();
	str2.display();
	str3.display();
	
	 
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值