zoukankan      html  css  js  c++  java
  • [C++] 类的动态内存分配

    asd

    #ifndef STRBAD_H_
    #define STRBAD_H_
    #include <iostream>
    
    class Strbad
    {
    public:
        Strbad(const char *s);
        Strbad();
        ~Strbad();
        
        //friend
        friend std::ostream & operator<<(std::ostream & os, const Strbad &st);
    
    private:
        char *str;
        int len;
        static int num_strings;
    
    };
    
    #endif //STRBAD_H_
    
    
    #include <iostream>
    #include <cstring>
    #include "strbad.h"
    using std::cout;
    
    int Strbad::num_strings = 0;
    
    Strbad::Strbad(const char *s)
    {
        len = std::strlen(s);
        str = new char[len+1];
        std::strcpy(str, s);
        num_strings++;
        cout<<num_strings<<": ""<<str<<""object created
    ";
    }
    
    Strbad::Strbad()
    {
        len = 4;
        str = new char[4];
        std::strcpy(str, "C++");
        num_strings++;
        cout<<num_strings<<": ""<<str<<""default object created
    ";
    }
    
    Strbad::~Strbad()
    {
        cout<<num_strings<<": ""<<str<<""object delete
    ";
        --num_strings;
        cout<<num_strings<<" left
    ";
        delete [] str;
    }
    
    std::ostream & operator<<(std::ostream &os, const Strbad &st)
    {
        os<<st.str;
        return os;
    }
    
    #include <iostream>
    #include "strbad.h"
    using std::cout;
    
    void callme1(Strbad &);
    void callme2(Strbad );
    
    int main()
    {
        using std::endl;
    
        cout<<"start an inner block
    ";
        Strbad headline1("Celery Stalks at MidNight");
        Strbad headline2("Lettuce Prey");
        Strbad sports("Spanish Leaves");
    
        cout<<"headline1:"<<headline1<<endl;
        cout<<"headline2:"<<headline2<<endl;
        cout<<"sports:"<<sports<<endl;
        callme1(headline1);
        cout<<"headline1:"<<headline1<<endl;
        callme2(headline2);
        cout<<"headline2:"<<headline2<<endl;
        cout<<"init one object to another:
    ";
        Strbad sailor = sports;
        cout<<"sailor:"<<sailor<<endl;
        cout<<"assign one object to another:
    ";
        Strbad knot;
        knot = headline1;
        cout<<"knot:"<<knot<<endl;
    
        cout<<"end of main
    ";
        return 0;
    }
    
    void callme1(Strbad &rsb)
    {
        cout<<"reference:
    ";
        cout<<" ""<<rsb<<""
    ";
    }
    
    void callme2(Strbad sb)
    {
        cout<<"value:
    ";
        cout<<" ""<<sb<<""
    ";
    }
  • 相关阅读:
    在Eclipse中指定JDK
    VMware桥接模式下主机和和虚机间互相ping不通的处理方法
    CentOS7系列--10.1CentOS7中的GNOME桌面环境
    CentOS7系列--5.3CentOS7中配置和管理Kubernetes
    CentOS7系列--5.2CentOS7中配置和管理Docker
    CentOS7系列--5.1CentOS7中配置和管理KVM
    CentOS7系列--4.1CentOS7中配置DNS服务
    CentOS7系列--3.2CentOS7中配置iSCSI服务
    移动web开发(一)——移动web开发必备知识
    文章索引
  • 原文地址:https://www.cnblogs.com/ingy0923/p/8691520.html
Copyright © 2011-2022 走看看