代码实现Cstring类成员函数
时间: 2023-04-05 19:02:29 浏览: 60
Cstring 类是一个字符串类,可以通过以下代码实现其成员函数:
```c++
class Cstring {
private:
char* str;
public:
Cstring(const char* s = nullptr); // 构造函数
Cstring(const Cstring& other); // 拷贝构造函数
~Cstring(); // 析构函数
int length() const; // 返回字符串长度
char& operator[](int index); // 重载下标运算符
const char& operator[](int index) const; // 重载下标运算符
Cstring& operator=(const Cstring& other); // 重载赋值运算符
Cstring operator+(const Cstring& other) const; // 重载加法运算符
bool operator==(const Cstring& other) const; // 重载相等运算符
bool operator!=(const Cstring& other) const; // 重载不等运算符
friend std::ostream& operator<<(std::ostream& os, const Cstring& str); // 重载输出运算符
};
```
其中,构造函数、拷贝构造函数和析构函数的实现如下:
```c++
Cstring::Cstring(const char* s) {
if (s == nullptr) {
str = new char[1];
str[0] = '\0';
} else {
int len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
}
Cstring::Cstring(const Cstring& other) {
int len = other.length();
str = new char[len + 1];
strcpy(str, other.str);
}
Cstring::~Cstring() {
delete[] str;
}
```
其它成员函数的实现可以根据需要进行编写。