#include <iostream>
#include <string.h>
using namespace std;
class String
{
public:
String(const char * str = NULL)
{
if (NULL == str)
{
cout << 1 << endl;
m_data = NULL;
}
else
{
cout << 2 << endl;
m_data = new char[strlen(str) + 1];
strcpy(m_data, str);
}
}
String(const String &other)
{
cout << 3 << endl;
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
}
~String(void)
{
delete[]m_data;
}
String & operator=(const String &other)
{
cout << 4 << endl;
delete[]m_data;
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
return *this;
}
String operator+(const String &other)
{
cout << 5 << endl;
char *p = new char[strlen(m_data) + strlen(other.m_data) + 1];
strcpy(p, m_data);
strcat(p, other.m_data);
String str(p);
return str;
}
friend void operator<<(ostream & out, String & obj);
private:
char * m_data;
};
void operator<<(ostream & out, String & obj)
{
cout << obj.m_data << endl;
}
int main(void)
{
String str("hello world");
cout << str ;
String str2 = "123456" ;
cout << str2;
String str3 = str;
cout << str3;
String str5;
str5 = str;
cout << str5;
String str4 = str + str2;
cout << str4;
return 0;
}
C++ 通过运算符重载实现String 类简单功能
最新推荐文章于 2023-01-01 18:57:25 发布