C++问题
#include <iostream>
#include <cstring>
struct MyString {
private:
char* str = nullptr;
public:
MyString(const char* src) {
printf("MyString(const char*)\n");
if (src == nullptr)
return;
str = (char*)malloc(strlen(src) + 1);
strcpy(str, src);
}
MyString() {
printf("MyString()\n");
};
MyString(const MyString& t) : str{nullptr} {
printf("MyString(const MyString&)\n");
if (t.str == nullptr)
return;
str = (char*)malloc(strlen(t.str) + 1);
strcpy(str, t.str);
}
~MyString() {
printf("~MyString()\n");
free(str);
}
MyString& operator=(const MyString& other) {
if (this == &other)
return *this;
free(str);
str = nullptr;
if (other.str == nullptr)
return *this;
str = (char*)malloc(strlen(other.str) + 1);
strcpy(str, other.str);
return *this;
}
MyString operator+(const MyString& other) {
MyString temp;
if (str == nullptr && other.str == nullptr)
return temp;
else if (str == nullptr)
temp = other;
else if (other.str == nullptr)
temp = *this;
else {
temp.str = (char*)malloc(strlen(str) + strlen(other.str) + 1);
strcpy(temp.str, str);
strcat(temp.str, other.str);
}
return temp;
}
MyString& operator+=(const MyString& other) {
char* temp = nullptr;
if (str == nullptr && other.str == nullptr)
return *this;
else if (str == nullptr)
temp = strdup(other.str);
else if (other.str == nullptr)
return *this;
else {
temp = (char*)malloc(strlen(str) + strlen(other.str) + 1);
strcpy(temp, str);
strcat(temp, other.str);
}
free(str);
str = temp;
return *this;
}
const char* c_str() const {
return str;
}
char& operator[](size_t index) {
return str[index];
}
};
int main() {
MyString c = {"Dmm"};
MyString a;
MyString d{" is a good man."};
a += c;
a += d;
a = a + c;
printf("%s\n", a.c_str());
a[0] = 'd';
printf("%s\n", a.c_str());
return 0;
}
我想输出
MyString(const char*)
MyString()
MyString(const char*)
Dmm is a good man.
dmm is a good man.
~MyString()
~MyString()
~MyString()
怎么改,感谢