对于如下的MyString片段,请补全必要的函数,使得main函数通过编译且正确运行。
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");
};
//拷贝构造函数 copy constructor
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;
}
};
int main() {
MyString c = {"Dmm"};
MyString a;
MyString d{" is a good man."};
a = a + c += d;
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()
感谢