[C++] 类的动态内存分配

时间:2022-03-20 20:02:09

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\n";
}

Strbad::Strbad()
{
    len = 4;
    str = new char[4];
    std::strcpy(str, "C++");
    num_strings++;
    cout<<num_strings<<": \""<<str<<"\"default object created\n";
}

Strbad::~Strbad()
{
    cout<<num_strings<<": \""<<str<<"\"object delete\n";
    --num_strings;
    cout<<num_strings<<" left\n";
    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\n";
    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:\n";
    Strbad sailor = sports;
    cout<<"sailor:"<<sailor<<endl;
    cout<<"assign one object to another:\n";
    Strbad knot;
    knot = headline1;
    cout<<"knot:"<<knot<<endl;

    cout<<"end of main\n";
    return 0;
}

void callme1(Strbad &rsb)
{
    cout<<"reference:\n";
    cout<<" \""<<rsb<<"\"\n";
}

void callme2(Strbad sb)
{
    cout<<"value:\n";
    cout<<" \""<<sb<<"\"\n";
}