设计一个mystring类,包括数据成员char * pstr; 和 int length; 通过运算符重载实现字符串的输入>>、输出<<、连接+=、赋值=、关系运算(==、!=、>、<)、下标[]等运算。
时间: 2024-05-15 18:14:35 浏览: 90
好的,我理解了您的要求。以下是设计的mystring类:
```cpp
#include <iostream>
#include <cstring>
class mystring {
private:
char *pstr;
int length;
public:
// 构造函数
mystring() {
pstr = nullptr;
length = 0;
}
// 带参构造函数
mystring(const char *str) {
if (str == nullptr) {
pstr = nullptr;
length = 0;
} else {
length = strlen(str);
pstr = new char[length + 1];
strcpy(pstr, str);
}
}
// 拷贝构造函数
mystring(const mystring &other) {
if (other.pstr == nullptr) {
pstr = nullptr;
length = 0;
} else {
length = other.length;
pstr = new char[length + 1];
strcpy(pstr, other.pstr);
}
}
// 析构函数
~mystring() {
delete[] pstr;
}
// 运算符重载
friend std::ostream& operator<<(std::ostream& os, const mystring& str) {
os << str.pstr;
return os;
}
friend std::istream& operator>>(std::istream& is, mystring& str) {
char buffer[1024];
is >> buffer;
if (str.pstr != nullptr) {
delete[] str.pstr;
}
str.length = strlen(buffer);
str.pstr = new char[str.length + 1];
strcpy(str.pstr, buffer);
return is;
}
mystring& operator=(const mystring& other) {
if (this == &other) {
return *this;
}
if (pstr != nullptr) {
delete[] pstr;
}
if (other.pstr == nullptr) {
pstr = nullptr;
length = 0;
} else {
length = other.length;
pstr = new char[length + 1];
strcpy(pstr, other.pstr);
}
return *this;
}
mystring operator+(const mystring& other) {
mystring result;
result.length = length + other.length;
result.pstr = new char[result.length + 1];
strcpy(result.pstr, pstr);
strcat(result.pstr, other.pstr);
return result;
}
bool operator==(const mystring& other) {
return strcmp(pstr, other.pstr) == 0;
}
bool operator!=(const mystring& other) {
return strcmp(pstr, other.pstr) != 0;
}
bool operator>(const mystring& other) {
return strcmp(pstr, other.pstr) > 0;
}
bool operator<(const mystring& other) {
return strcmp(pstr, other.pstr) < 0;
}
char operator[](int index) {
if (index >= 0 && index < length) {
return pstr[index];
} else {
return '\0'; // 空字符表示越界或者字符串为空
}
}
};
```
您可以在代码中按需修改数据成员的名称和类型,或者添加其他需要实现的功能。但请保证数据成员和运算符重载的定义与本示例代码的要求一致,以确保代码能够正确运行。
阅读全文