zoukankan      html  css  js  c++  java
  • 继承与动态内存分配

    #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;
    }
  • 相关阅读:
    搞笑视频分析---1、老番茄-最强间谍王
    尚学linux课程---11、vim操作命令1
    php开发面试题---php缓存总结
    legend2---17、legend2里面怎么面向对象
    北风设计模式课程---10、创建型的设计模式对比总结
    北风设计模式课程---8、装饰器模式
    Linux下安装Tomcat服务器
    种子软件下载种子慢怎么解决
    php开发面试题---Redis和Memcache区别,优缺点对比
    Make a dent in the universe
  • 原文地址:https://www.cnblogs.com/achao123456/p/9695243.html
Copyright © 2011-2022 走看看