您的位置:首页 > 编程语言 > C语言/C++

用C++封装一个String

2016-04-16 11:17 441 查看
习惯了C#跟Java以后,使用C++是各种不方便,主要是封装太少,其次C++中的对象思想其实用得并不广泛,而是强调指针,正在努力习惯中。

跟着课程封装了string

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

MyString * MyString::ms = NULL;

MyString* MyString::MakeMyString(const char *s)
{
if(ms==NULL)
{
if(s==NULL)
{
ms = new MyString();
}else
{
ms = new MyString(s);
}
}
return ms;
}

void MyString::set_string(const char *s)
{
if(this->s==NULL)
{
int str_len =strlen(s);
this->s = new char[str_len+1];
strcpy(this->s,s);
this->s[str_len] = 0;
}
else
{
int str_len = strlen(s);
delete []this->s;
this->s = new char[str_len+1];
strcpy(this->s,s);
this->s[str_len] = 0;
}
}

char * MyString::getString() const
{
return s;
}

void MyString::releaseString()
{
if(ms!=NULL)
{
delete ms;
ms = NULL;//以供下次再次使用
// return ;
}else
{
// return ;
}
}

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()
{
delete []s;

}

MyString::MyString(const MyString &it)
{
this->s = new char [strlen(it.s)+1];
strcpy(this->s,it.s);
this->s = 0;

}


mystring头文件

#ifndef MYSTRING_H
#define MYSTRING_H

class MyString
{
private:
static MyString *ms;
char *s;

public:
static MyString* MakeMyString(const char *s);
void set_string(const char *s);
char* getString()const;
void releaseString();

protected:
MyString();
MyString(const char *s);
~MyString();
MyString(const MyString &it);
};

#endif // MYSTRING_H


总结起来,这个跟java的私有化结构函数思想一样,但是这个主要是操作指针、数组。学到的东西:new 出来的东西一定要delete,如果下次需要重新使用需要将其置为NULL;

深拷贝的使用方法与情况(有指针存在的时候)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: