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<<""
    ";
    }
  • 相关阅读:
    layer弹出层显示在top顶层
    PC上安装多个操作系统
    Windows下DLL查找顺序
    AHCI驱动安装
    Office 多版本共存
    Windows定时器
    Windows菜单
    Windows高精度时间
    VB6.0调用DLL
    时间服务器通讯协议
  • 原文地址:https://www.cnblogs.com/ingy0923/p/8691520.html
Copyright © 2011-2022 走看看