天天看點

指派運算符函

指派運算符函

#include <iostream>
#include <cstring> 
using namespace std;

class String
{
    public:
        String(const char *s=nullptr);//自定義構造函數 
        String(const String &s1);//拷貝構造哈數 
        String &operator=(const String &s);//指派構造函數 
        void print();
    private:
        char *data;
};

String::String(const char *s)
{
    if(s==NULL)
    {
        data=new char[1];
        data[0]='\0';
    }
    else
    {
        data=new char[strlen(s)+1];
        strcpy(data,s);
    }
}

String::String(const String &s1)
{    
    data=new char[strlen(s1.data)+1];
    strcpy(data,s1.data);
    //cout<<" copy."<<endl;
}

String &String::operator=(const String &s)
{
    if(&s==this)//防止自己指派 
        return *this;
    
    delete []data;
    data=new char[strlen(s.data)+1];
    strcpy(data,s.data);
    //cout<<" operator=."<<endl;
}

void String::print() 
{
    cout<<data<<endl;
}

int main()
{
    String s("hello word.");//自定義構造函數 
    String s2=s;//拷貝構造函數 
    String s3(s2);//s3需要用s2初始化,調用拷貝構造函數 
    s2=s3;//s2,s3已存在。調用指派構造函數 ;當一個類的對象向該類的另一個對象指派時,就會用到該類的指派函數。首先該對象要存在 
    s2.print();
    s3.print();
    return 0;
}