#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;
}
String的构造函数拷贝构造函数
最新推荐文章于 2022-07-31 21:45:36 发布