码迷,mamicode.com
首页 > 其他好文 > 详细

继承与动态内存分配

时间:2018-09-24 13:51:21      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:std   ase   ring   creat   内存分配   virtual   []   using   rtu   

#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] = \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] = \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;
}

 

继承与动态内存分配

标签:std   ase   ring   creat   内存分配   virtual   []   using   rtu   

原文地址:https://www.cnblogs.com/achao123456/p/9695243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!