您的位置:首页 > 编程语言 > Lua

lua 小知识

2016-07-02 15:46 405 查看
1.编写类String的构造函数,析构函数和赋值函数,已知类String用成员变量char* _str

来保存字符串

//普通的构造函数

String::String(const char* str)

{

if(str == NULL)

{

_str = new char[1];//对空字符串自动申请存放‘\0’的空间

*_str = '\0';

}

else

{

int length = strlen(str);

_str = new char[length+1];//若能加NULL判断则更好

strcpy(_str,str);

}

}

//String 的析构函数

String::~String(void)

{

delete[]_str;

}

//拷贝构造函数

String::String(const String &other)//输入参数为const型

{

int length = strlen(other._str);

_str = new char[length+1];//对_str加NULL 判断

strcpy(_str,other._str);

}

//赋值函数

String & String::operate = (const String &other)

{

if(this ==&other)

{

return *this;

}

delete[]_str;

int length = strlen(other._str);

_str = new char[length+1];

strcpy(_str,other._str);

return *this;

}

2.c语言的strcpy函数

char * strcpy(char*strDest,const char*strSrc)

{

assert((strDest!NULL)&&(strSrc!=NULL));

char*address= strDest;

while((*strDest++=*strSrc++)!='\0')NULL;

return address;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: