作业:自行实现一个Mystring类
#include <iostream>
#include <cstring>
using namespace std;
class Mystring
{
public:
Mystring() : str(nullptr), len(0) {}
Mystring(const char* s) : len(strlen(s)), str(new char[len + 1])
{
strcpy(str, s);
cout<<"有参构造函数"<<endl;
}
// 拷贝构造函数
Mystring(const Mystring& other) : len(other.len), str(new char[other.len + 1])
{
strcpy(str, other.str);
cout<<"拷贝构造函数"<<endl;
}
// 拷贝赋值函数
Mystring& operator=(const Mystring& other)
{
if (this != &other)
{
delete[] str;
len = other.len;
str = new char[len + 1];
strcpy(str, other.str);
}
cout<<"拷贝赋值函数"<<endl;
return *this;
}
// 析构函数
~Mystring()
{
if (str != nullptr)
delete[] str;
}
// 成员函数
const char* c_str() const
{
return str;
}
size_t length() const
{
return len;
}
bool empty() const
{
return len == 0;
}
private:
char* str;
size_t len;
};
int main(int argc,char *argv[])
{
Mystring str1("Hello");
Mystring str2 = str1; // 使用拷贝构造函数
cout << "str2: " << str2.c_str() << endl;
cout << "Length of str2: " << str2.length() << endl;
cout << "Is str2 empty? " << (str2.empty() ? "Yes" : "No") << endl;
return 0;
}