/*
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;
}
c++学习-oop-重载自增自减操作符
最新推荐文章于 2022-11-16 22:21:14 发布