美文网首页
C++ String 类

C++ String 类

作者: 奇点创客 | 来源:发表于2020-02-08 18:48 被阅读0次

    源码

    #include <iostream>
    #include <cstring>
    
    #pragma warning(disable : 4996)  // for MSVC
    
    class String
    {
    public:
        String(const char* str = nullptr) {
            if (str == nullptr) {
                data_ = new char[1];
                *data_ = '\0';
                std::cout << "Default constructor" << std::endl;
            }
            else {
                int length = strlen(str);
                data_ = new char[length + 1];
                std::strcpy(data_, str);
                std::cout << "Pass argument constructor" << std::endl;
            }
            
        }
        
        String(const String& other) {
            int length = strlen(other.data_);
            data_ = new char[length + 1];
            std::strcpy(data_, other.data_);
            std::cout << "Copy constructor" << std::endl;
        }
    
        String& operator=(const String& other) {
            if (this != &other) {
                if (!data_) delete[] data_;
                int length = strlen(other.data_);
                data_ = new char[length + 1];
                strcpy(data_, other.data_);
            }
            std::cout << "Copy assignment" << std::endl;
            return *this;
        }
    
        ~String() {
            delete[] data_;
            std::cout << "Destructor" << std::endl;
        }
    
        String(String&& other) noexcept {
            data_ = other.data_;
            other.data_ = nullptr;
            std::cout << "Move constructor" << std::endl;
        }
    
        String& operator=(String&& other) noexcept {
            if (this != &other) {
                delete[] data_;
                data_ = other.data_;
                other.data_ = nullptr;
            }
            std::cout << "Move assignment" << std::endl;
            return *this;
        }
    
    private:
        char* data_;
    };
    
    
    int main()
    {  
        // 测试:默认构造
        String s1;
    
        // 测试:传参构造
        String s2("Hello world!");
    
        // 测试:拷贝构造
        String s3(s1);
    
        // 测试:移动构造
        String s4(std::move(s3));
    
        // 测试:拷贝赋值
        String s5;
        s5 = s4;
    
        // 测试:移动赋值
        String s6;
        s6 = std::move(s5);
    
        return 0;
    }
    

    运行结果


    Result

    相关文章

      网友评论

          本文标题:C++ String 类

          本文链接:https://www.haomeiwen.com/subject/tyaixhtx.html