#include <iostream>
#include <cstring>
class Mystring
{
public:
// 默认构造函数
Mystring() : str(nullptr), len(0) {}
// 有参构造函数
Mystring(const char* s)
{
len = strlen(s);
str = new char[len + 1]; // 分配空间,并多留一个位置给'\0'
strcpy(str, s);
}
// 拷贝构造函数
Mystring(const Mystring& other)
{
len = other.len;
str = new char[len + 1];
strcpy(str, other.str);
}
// 拷贝赋值操作符
Mystring& operator=(const Mystring& other)
{
if (this == &other)
{
return *this; // 检查自赋值
}
delete[] str; // 删除旧的字符串数据
len = other.len;
str = new char[len + 1];
strcpy(str, other.str);
return *this;
}
// 析构函数
~Mystring()
{
delete[] str;
}
// 获取字符串的C风格表示
const char* c_str() const
{
return str;
}
// 获取字符串长度
int size() const
{
return len;
}
// 获取字符串长度
int length() const
{
return len;
}
// 判断字符串是否为空
bool empty() const
{
return len == 0;
}
// 获取字符串中某个位置的字符
char& at(int index)
{
if (index < 0 || index >= len)
{
throw std::out_of_range("Index out of range");
}
return str[index];
}
// 常量版本的at函数
const char& at(int index) const
{
if (index < 0 || index >= len)
{
throw std::out_of_range("Index out of range");
}
return str[index];
}
private:
char* str; // 指向字符串的指针
int len; // 字符串长度
};
int main() {
Mystring s1("Hello");
Mystring s2(s1); // 使用拷贝构造函数
Mystring s3;
s3 = s1; // 使用拷贝赋值操作符
std::cout << "s1: " << s1.c_str() << ", size: " << s1.size() << std::endl;
std::cout << "s2: " << s2.c_str() << ", size: " << s2.size() << std::endl;
std::cout << "s3: " << s3.c_str() << ", size: " << s3.size() << std::endl;
std::cout << "s1 at 1: " << s1.at(1) << std::endl;
std::cout << "Is s1 empty? " << (s1.empty() ? "Yes" : "No") << std::endl;
return 0;
}
08-11
1090
08-30
4074
09-02
417
08-29
2563