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

C++复习第一天 静态类成员实现单例模式

2017-09-18 08:32 204 查看
/*********************************mystring.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);

};

#endif // MYSTRING_H

/*********************************mystring.cpp*******************************/
//include "mystring.h"
#include <iostream>
#include <string.h>
//初始化类静态成员变量,
mystring *mystring::self = NULL;   //sm上面shi上面是shengm上面是声明,zhel这里shi这里是dingyi
//创建一个单例类对象
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,这样就可以再次建立类的实例,因为makestring有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)  //默认构造函数中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
}
}
}

/*********************************main.cpp*******************************/
#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;
}
//运行结果 打印输出hello world
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: