您的位置:首页 > 其它

String的构造函数拷贝构造函数

2015-12-24 09:10 316 查看
#include<iostream>
using namespace std;

class String
{
private:
char *m_Str;
protected:
public:

String(const char *str = NULL)
{
if (str == NULL)
{
m_Str = new char[1];
*m_Str = '\0';
}
else
{
int size = strlen(str);
m_Str = new char[size + 1];
strcpy(m_Str, str);
}
}
String(const String &other)//拷贝构造函数
{
int length = strlen(other.m_Str);
m_Str = new char[length + 1];
strcpy(m_Str, other.m_Str);
}
String& String::operator =(const String &other)
{
if (this == &other)//当地址相同时,直接返回;
return *this;

delete[] m_Str;//当地址不相同时,删除原来申请的空间,重新开始构造;

int length = strlen(other.m_Str);
m_Str = new char[length + 1];
strcpy(m_Str, other.m_Str);

return *this;
}
~String()
{
delete[]m_Str;
}
friend ostream &operator<<(ostream &out,String &s)
{
out << s.m_Str;
return out;
}
};
int main(int argc, char * argv[])
{
String s("abc");

cout << s << endl;

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