하위 클래스의 복사, 값 부여 구조 함수 부모 클래스 구성원 잊지 않기

2593 단어 deleteClassreference
#include<iostream>
using namespace std;
class Base
{
    public:
        Base(char *_name){int len=strlen(_name);if(len==0){name=new char[1];name[0]='/0';}
            else{name=new char[len+1];strcpy(name,_name);}cout<<"creat "<<name<<endl;} 
        Base(const Base &b){name=new char[strlen(b.name)+1];strcpy(name,b.name);cout<<"copy "<<name<<endl;}
        Base &operator=(const Base &b){if(this==&b)return *this;delete []name;;name=new char[strlen(b.name)+1];strcpy(name,b.name);cout<<"assign "<<name<<endl;return *this;}
            virtual ~Base(){cout<<"del "<<name<<endl;delete []name;}
    private:
        char *name;
};

class Derived:virtual public Base//effective in multiple inherit
{
    public:
        Derived(char *_name,char *_descrip):Base(_name)
            {
            int len=strlen(_descrip);
            if(len==0)
            {
                descrip=new char[1];
                descrip[0]='/0';
            }
            else
            {
                descrip=new char[len+1];
                strcpy(descrip,_descrip);
            }
            cout<<"creat "<<descrip<<endl;
        }
        Derived(const Derived &d):Base(d){descrip=new char[strlen(d.descrip)+1];strcpy(descrip,d.descrip);cout<<"copy "<<descrip<<endl;}//do remember to intitialize parent's data members in this way
        Derived &operator=(const Derived &d)
        {
            if(this==&d)
                return *this;
            Base::operator=(d);//call this if = is overlapped in the base class
            //static_cast<&Base>(*this)=d;call this if = not overlapped,and reference a must!
            delete []descrip;
            descrip=new char[strlen(d.descrip)+1];
            strcpy(descrip,d.descrip);
            cout<<"assign "<<descrip<<endl;
            return *this;
        }
        ~Derived(){cout<<"del "<<descrip<<endl;delete []descrip;}
    private:
        char *descrip;
};
int main()
{
    Derived d1("a","best");
    Derived d2(d1);
    cout<<endl<<endl;
    Derived d3("b","great");
    d2=d3;
    cout<<endl<<endl;
}


prayaya@prayaya:~/Desktop/lab$ ./a.out
creat a
creat best
copy a
copy best


creat b
creat great
assign b
assign great


del great
del b
del great
del b
del best
del a

좋은 웹페이지 즐겨찾기