C++动态分配内存的字符串

Mysring.h文件

#ifndef MYSTRING_H
#define MYSTRING_H

#include <iostream>

//一个单例的能够动态分配内存的字符串
class mystring
{
private:
    static mystring *self;
    char *s;
public:
    static mystring *makestring(const char *s = NULL);
    static void deletestring();

    ~mystring();
    const char *get_s() const;
    void set_s(const char *s);


protected:
    mystring();
    mystring(const char *s);
    mystring(const mystring &it);

};

mystring.cpp文件

#include "mystring.h"
#include <iostream>
#include <string.h>

mystring *mystring::self = NULL;

mystring *mystring::makestring(const char *s)
{
    if (self == NULL)
    {
        if (s == NULL)
            self = new mystring;
        else
            self = new mystring(s);
    }

    return self;
}

void mystring::deletestring()
{
    if (self != NULL)
    {
        delete self;
        self = NULL;//释放指针之后,赋值NULL,这样就可以再次建立类的实例
    }
}

mystring::mystring(): s(NULL)
{

}

mystring::mystring(const char *s)
{
    int len = strlen(s);
    this->s = new char[len + 1];
    strcpy(this->s, s);
    this->s[len] = 0;
}

mystring::mystring(const mystring &it)//通过拷贝构造实现深拷贝,避免成员变量指针赋值导致的错误
{
    int len = strlen(it.get_s());
    this->s = new char[len + 1];
    strcpy(this->s, it.s);
    this->s[len] = 0;
}

mystring::~mystring()
{
    delete []s;//将构造函数分配的内存释放
}

const char *mystring::get_s() const
{
    return s;
}

void mystring::set_s(const char *s)
{
    if (this->s == NULL)
    {
        int len = strlen(s);
        this->s = new char[len + 1];
        strcpy(this->s, s);
        this->s[len] = 0;
    }else
    {
        int len1 = strlen(this->s);
        int len2 = strlen(s);

        if (len1 > len2)
        {
            strcpy(this->s, s);
            this->s[strlen(s)] = 0;
        }else
        {
            delete []this->s;//由于成员变量s的空间不够了,所以不要了
            this->s = new char[len2 + 1];//重新给成员变量s分配新空间
            strcpy(this->s, s);//给新空间赋值
            this->s[len2] = 0;//新空间最后一个字节为字符串结束标示符0
        }
    }
}

测试主函数

#include <iostream>
#include "mystring.h"

using namespace std;

int main()
{
//    mystring str1("hello world");
//    mystring str2 = str1;
//    str3.set_s("SDFSD");
//    cout << str1.get_s() << endl;
    //mystring *str1 = mystring::makestring();//默认调用的是NULL

    mystring *str1 = mystring::makestring("hello world");//默认调用的是NULL

    cout << str1->get_s() << endl;

    mystring::deletestring();

    mystring *str3 = mystring::makestring("aaaaaaa");

    cout << str3->get_s() << endl;

    return 0;
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值