String类的构造
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include"stdafx.h"
#include
class String
{
public:
String(const char *str = ""); //普?通ª¡§构1造¨¬
String(const String& other); //拷?贝À¡ä
String& operator=(const String& other); //复¡ä制?
~String(void); //析?构1
char *GetString() const;
private:
char *m_data; //保À¡ê存ä?字Á?符¤?串ä?
};
String::String(const char *str)
{
if (str != NULL)
{
int n = strlen(str);
m_data = new char[n+1];
strcpy(m_data, str);
}
else
{
m_data = new char[1];
*m_data = '\0';
}
};
String::~String(void)
{
delete []m_data;
}
String::String(const String& other)
{
int n = strlen(other.m_data);
m_data = new char[n+1];
strcpy(m_data, other.m_data);
}
String& String::operator=(const String& other)
{
if (this != &other) //检¨¬查¨¦自Á?赋3值¦Ì
{
char *temp = new char[strlen(other.m_data)+1]; //分¤?配?新?的Ì?内¨²存ä?资Á¨º源¡ä,ê?并¡é拷?贝À¡ä内¨²容¨Y
strcpy(temp, other.m_data);
delete []m_data; //释º¨ª放¤?原-有®D的Ì?内¨²存ä?资Á¨º源¡ä
m_data = temp;
delete []temp;
}
return *this; //返¤¦Ì回?本À?对?象¨®引°y用®?
}
char *String::GetString() const
{
return m_data;
}
int_tmain(int argc, _TCHAR* argv[])
{
String s("Hello World");
String s1 = s;
String s2(s);
printf("%s\n", s.GetString());
printf("%s\n", s1.GetString());
printf("%s\n", s2.GetString());
return 0;
}