继承与动态内存分配

#include <iostream>
#include <cstring>

using namespace std;

class base
{
private:
    char *label;
public:
    virtual ~base();
    base();
    base(char *s);
    base(const base &b);
    const base &operator=(const base &b);
    virtual void print();
};

base::~base()
{
    cout<<"class f destructor"<<endl;
    delete [] label;
}

base::base()
{
    label = new char[1];
    label[0] = '';
}

base::base(char *s)
{
    label = new char[strlen(s)+1];
    strcpy(label,s);
}

base::base(const base &b)
{
    label = new char[strlen(b.label)+1];
    strcpy(label,b.label);
}

const base & base::operator=(const base &b)
{
    if(this == &b)
    {
        return *this;
    }
    delete [] label;
    this->label = new char[strlen(b.label)+1];
    strcpy(this->label,b.label);
    return *this;
}

void base::print()
{
    cout<<"class f print"<<endl;
    cout<< label <<endl;
}

class create:public base
{
private:
    char *style;
public:
    virtual ~create();
    create();
    create(char *s1,char *s2);
    create(const create &c);
    const create & operator=(const create &c);
    virtual void print();
};

create::~create()
{
    cout<< "class s destructor"<<endl;
    delete [] style;
}

create::create()
{
    style = new char[1];
    style[0] = '';
}

create::create(char *s1,char *s2):base(s2)
{
    style = new char[strlen(s1)+1];
    strcpy(style,s1);
}

create::create(const create &c):base(c)
{
    style = new char[strlen(c.style)+1];
    strcpy(style,c.style);
}

const create & create::operator=(const create &c)
{
    if(this == &c)
    {
        return *this;
    }
    base::operator=(c);
    delete [] style;
    this->style = new char[strlen(c.style)+1];
    strcpy(this->style,c.style);
    return *this;
}

void create::print()
{
    cout<< "class s print" <<endl;
    cout<< style <<endl;
}

int main()
{
    base b1;
    base b2("base label");
    create c1;
    create c2("create style","laji");
    
    b2.print();
    c2.print();

    return 0;
}
原文地址:https://www.cnblogs.com/achao123456/p/9695243.html