• cc22a_demo_c++重载自增自减操作符代码示范


    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;
    }
    欢迎讨论,相互学习。 txwtech@163.com
  • 相关阅读:
    洛谷P1043数字游戏
    luogu P1330 封锁阳光大学
    luoguP1242 新汉诺塔
    luogu P1892 [BOI2003]团伙
    luogu P3375 【模板】KMP字符串匹配
    luoguP1440 求m区间内的最小值
    luoguP2700 逐个击破
    luoguP2814 家谱
    luogu P1962 斐波那契数列
    P3379 【模板】最近公共祖先(LCA)
  • 原文地址:https://www.cnblogs.com/txwtech/p/12103045.html
Copyright © 2020-2023  润新知