c++中赋值运算符重载

来源:互联网 发布:阿里云个人域名备案 编辑:程序博客网 时间:2024/06/06 04:16
#include<iostream>#include <stdio.h>using namespace std;class string1{private:    char *ptr;    public:     string1(char *s)     {         ptr=new char[strlen(s)+1];         strcpy(ptr,s);     }     ~string1()     {         delete ptr;         cout<<"调用了析构函数"<<endl;     }     void print()     {         cout<<ptr<<endl;     }     string1(const string1 &p)     {      //拷贝构造函数        ptr=new char[strlen(p.ptr)+1];        strcpy(ptr,p.ptr);        cout<<"调用了拷贝构造函数"<<endl;     }    string1  &operator=(const string1 & s)    {        if(this==&s)   return *this;        delete ptr;        ptr=new char[strlen(s.ptr)+1];        strcpy(ptr,s.ptr);        return *this;  /* 如果返回的不是引用就会调用拷贝构造函数  如果没有自己定义拷贝构造函数,会出问题加上拷贝构造函数的话也可以实现连续赋值的情况,不过中间会调用两次析构函数*/    }};int main(){    {string1 p1=("book");    string1 p2("pen");    string1 p3("pen");    p3=p2=p1;    cout<<"p2";    p2.print();    cout<<"p1:";    p1.print();    cout<<"P3";    p3.print();}    getchar();    return 0;}
0 0
原创粉丝点击