64,637
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
using namespace std;
class MyString
{
private:
int len;
char* buffer;
public:
MyString() :len(1), buffer(new char[1])
{
buffer[0] = '\0';
}
MyString(const MyString&);
MyString(const char*);
MyString& operator=(const MyString&);
MyString& operator=(const char*);
MyString& operator=(MyString&&);
~MyString();
int size() const;
char* data() const;
MyString& operator+=(const MyString&);
friend MyString operator+(const MyString&, const MyString&);
operator char*();
};
MyString::MyString(const MyString& str)
{
cout << "copy constructor" << endl;
len = str.size() + 1;
if (buffer != NULL)
delete[] buffer;
buffer = new char[len];
strcpy(buffer, str.data());
}
MyString::MyString(const char* chStr)
{
int i = 0;
while (chStr[i++] != 0);
len = i;
if (buffer != NULL)
delete[] buffer;
buffer = new char[len];
strcpy(buffer, chStr);
}
MyString& MyString::operator=(const MyString& str)
{
len = str.size() + 1;
if (buffer != NULL)
delete[] buffer;
buffer = new char[len];
strcpy(buffer, str.data());
return *this;
}
MyString& MyString::operator=(MyString&& str)
{
len = str.size() + 1;
if (buffer != NULL)
delete[] buffer;
buffer = new char[len];
strcpy(buffer, str.data());
str.len = 1;
if (buffer != NULL)
delete[] str.buffer;
str.buffer = new char[1];
str.buffer[0] = '\0';
return *this;
}
MyString& MyString::operator=(const char* chStr)
{
int i = 0;
while (chStr[i++] != 0);
len = i;
if (buffer != NULL)
delete[] buffer;
buffer = new char[len];
strcpy(buffer, chStr);
return *this;
}
MyString::~MyString()
{
if (buffer != NULL)
delete[] buffer;
cout << "destructor" << endl;
}
int MyString::size() const
{
return len - 1;
}
char* MyString::data() const
{
return buffer;
}
MyString::operator char*()
{
cout << "operator char*" << endl;
return buffer;
}
MyString operator+(const MyString& str1, const MyString& str2)
{
cout << "operator + begin" << endl;
int n1, n2;
char * S;
n1 = strlen(str1.buffer);
n2 = strlen(str2.buffer);
S = new char[n2 + n1 + 1];
strcpy(S, str1.buffer);
strcat(S, str2.buffer);
MyString S1(S);
cout << S1 << endl;
cout << "operator + end" << endl;
return S1;
}
int main()
{
MyString s1("123");
MyString s2 = "456";
cout << s1+s2 << endl;
return 0;
}