【问题描述】基于char *设计一个字符串类MyString。具有构造函数、析构函数、拷贝构造函数、重载运算符“+”、“=”、“+=”、“[]”等 尽可能地完善,使之能满足各种需求 。
【输入形式】无
【输出形式】
【样例输入】无
【样例输出】
S1:initial test
S1:Hello World
tempTwo:; nice to be here!
S1:Hello World; nice to be here!
S1[4]😮
S1:Hellx World; nice to be here!
S1[999]:!
S3:Hellx World; nice to be here! Another myString
S4:Why does this work?
【样例说明】
【评分标准】
代码如下:
#include<bits/stdc++.h>
using namespace std;
// 类MyString的设计与实现
class MyString {
public:
MyString(const char* str = "") {
myString = new char[strlen(str) + 1];
strcpy(myString, str);
}
MyString(const MyString& other) {
myString = new char[strlen(other.myString) + 1];
strcpy(myString, other.myString);
}
~MyString() {
delete[] myString;
}
MyString& operator=(const MyString& other) {
if (this != &other) {
delete[] myString;
myString = new char[strlen(other.myString) + 1];
strcpy(myString, other.myString);
}
return *this;
}
MyString& operator=(const char* str) {
delete[] myString;
myString = new char[strlen(str) + 1];
strcpy(myString, str);
return *this;
}
MyString operator+(const MyString& other) const {
MyString result;
result.myString = new char[strlen(myString) + strlen(other.myString) + 1];
strcpy(result.myString, myString);
strcat(result.myString, other.myString);
return result;
}
MyString& operator+=(const char* str) {
char* temp = new char[strlen(myString) + strlen(str) + 1];
strcpy(temp, myString);
strcat(temp, str);
delete[] myString;
myString = temp;
return *this;
}
char& operator[](size_t index) {
if (index >= strlen(myString)) {
return myString[strlen(myString) - 1];
}
return myString[index];
}
const char* getMyString() const {
return myString;
}
private:
char* myString;
};
int main() {
MyString s1("initial test");
cout << "S1:\t" << s1.getMyString() << endl;
char* temp = "Hello World";
s1 = temp;
cout << "S1:\t" << s1.getMyString() << endl;
char tempTwo[25];
strcpy(tempTwo, "; nice to be here!");
s1 += tempTwo;
cout << "tempTwo:\t" << tempTwo << endl;
cout << "S1:\t" << s1.getMyString() << endl;
cout << "S1[4]:\t" << s1[4] << endl;
s1[4] = 'x';
cout << "S1:\t" << s1.getMyString() << endl;
cout << "S1[999]:\t" << s1[999] << endl;
MyString s2(" Another myString");
MyString s3;
s3 = s1 + s2;
cout << "S3:\t" << s3.getMyString() << endl;
MyString s4;
s4 = "Why does this work?";
cout << "S4:\t" << s4.getMyString() << endl;
return 0;
}