zoukankan      html  css  js  c++  java
  • c++ 移动构造函数

    1 c++ 移动构造函数.cpp

    #include<iostream>
    #include<string.h>
    using namespace std;
    
    class my_string{
        char* p=nullptr;
        public:
        my_string(){}
        my_string(const char* s){
            if(s){
                p = new char[strlen(s)+1];
                strcpy(p,s);
            }
        }
        my_string( const my_string& ms){
            cout<<"copy construction"<<endl;
            if(ms.p){
                if(p)delete []p;
                p = new char[ms.size()+1];
                strcpy(p,ms.p);
            }
        }
        ~my_string(){
            if(p)delete [] p;
        }
        my_string(my_string && s)
        {
            cout<<"move construction"<<endl;
            p = s.p;
            s.p =nullptr;
        }
    friend ostream &operator<<(ostream&cout,my_string s);
        char & operator[](int pos)
        {
            return p[pos];
        }
        int size()const{return strlen(p);}
        my_string operator+(my_string &s)
        {
            my_string tmp;
            tmp.p= new char[this->size()+s.size()+1];
            strcpy(tmp.p,this->p);
            strcat(tmp.p,s.p);
            return tmp;
        }
        my_string operator+(const char* s)
        {
            my_string tmp;
            tmp.p= new char[this->size()+strlen(s)+1];
            strcpy(tmp.p,this->p);
            strcat(tmp.p,s);
            return tmp;
        }
    };
    
    ostream &operator<<(ostream&cout,my_string s)
    {
        cout<<s.p;
        return cout;
    }
    
    int main()
    {
        my_string s1="123";
        my_string s2="456";
        my_string s3(std::move(s1));
    //  cout<<s1<<endl;//s1已经指向nullptr,所以不要被打印,否则结果未知
        cout<<s2<<endl;
        cout<<s3<<endl;
    //  cout<<s1+s2<<endl;
        return 0;
    }
    
  • 相关阅读:
    win10重装vscode后打不开
    GDB 调试
    分布式架构--概述一
    汇编语言答案(王爽)第三版
    matplotlib之热成像图
    matplotlib之等高线图
    matplotlib之饼状图
    matplotlib之条形图绘制
    360图片网站批量抓取
    数据转换
  • 原文地址:https://www.cnblogs.com/Sico2Sico/p/5384238.html
Copyright © 2011-2022 走看看