继承与动态内存分配

Posted achao123456

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了继承与动态内存分配相关的知识,希望对你有一定的参考价值。

#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;
}

 

以上是关于继承与动态内存分配的主要内容,如果未能解决你的问题,请参考以下文章

C与C++申请动态内存空间的异同

动态内存分配与静态内存分配

Golang 1.14中内存分配、清扫和内存回收

每日一练5

C++ 单例类实例的堆/动态与静态内存分配

C - 读取文件并将文本放入具有动态内存分配的字符指针