cc22a_demo_c++重载自增自减操作符-代码示范
#define _CRT_SECURE_NO_WARNINGS #include <iostream> 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 (std::size_t i = 0; i < std::strlen(ptrChars); ++i) { ++ptrChars[i]; } return *this; } String const String::operator++(int n) //int自动设置为0 { String copy(*this); ++(*this); return copy; } String::String(char const *chars) { chars = chars ? chars : ""; ptrChars = new char[std::strlen(chars)+1]; std::strcpy(ptrChars,chars); } String::String(String const &str) { ptrChars = new char[std::strlen(str.ptrChars) + 1]; std::strcpy(ptrChars,str.ptrChars); } String::~String() { delete[] ptrChars; } void String::display() const { cout << ptrChars << endl; } int main() { int x = 5; x++; ++x; //cout << x << endl; String s("ABC"); s.display(); ++s; s.display(); ++s; s.display(); cout << endl; String str1("ABC"); str1.display(); String str2(++str1); str2.display(); String str3(str1++); str3.display(); str1.display(); // cout << "hello" << endl; system("pause"); return 0; }