设计一个自己的字符串类MyString,内部有一个私有成员char *sptr;该成员用于创建字符串对象时,在内部使用动态内存分配的方法分配一个字符数组用于存储字符串的内容。
输入描述本题无输入
输出描述按样例输出
提示你需要提交除了main函数之外的其他代码,可以使用C中的字符串处理函数帮助你的处理
样例输入
样例输出
Object Constructed. No Memory Allocated.
Object Constructed. 6 Bytes Allocated.
Object Constructed. 6 Bytes Allocated.
No Memory Allocated In This Object.
Hello
Hello
0 5 5
Object Constructed. 8 Bytes Allocated.
String Copy, 8 Bytes Reallocated And 6 Bytes Freed.
HiChina
String Connection, 13 Bytes Reallocated And 6 Bytes Freed.
HelloHiChina
Object Destructed. 8 Bytes Freed.
Object Destructed. 13 Bytes Freed.
Object Destructed. 8 Bytes Freed.
Object Destructed. No Memory Freed.
#include<stdio.h>
#include <iostream>
#pragma warning(disable:4996)
#include <string.h>
using namespace std;
class MyString
{
private:
char* sptr;
public:
MyString()
{
sptr = new char[1];
sptr[0] = '\0';
cout << "Object Constructed. No Memory Allocated." << endl;
}
MyString(const char* p)
{
sptr = new char[strlen(p) + 1];
strcpy(sptr, p);
cout << "Object Constructed. " << strlen(p) + 1 << " Bytes Allocated." << endl;
}
MyString(const MyString& str)
{
sptr = new char[strlen(str.sptr) + 1];
strcpy(sptr, str.sptr);
cout << "Object Constructed. " << strlen(str.sptr) + 1 << " Bytes Allocated." << endl;
}
~MyString()
{
if (sptr[0] == '\0')
{
delete[]sptr;
cout << "Object Destructed. No Memory Freed." << endl;
}
else
{
cout << "Object Destructed. " << strlen(sptr) + 1 << " Bytes Freed." << endl;
delete[]sptr;
}
}
void printString()
{
if (sptr[0] == '\0')cout << "No Memory Allocated In This Object." << endl;
else cout << sptr << endl;
}
int getSize()
{
int p = (strlen(this->sptr));
return p;
}
void stringCopy(const MyString& s)
{
cout << "String Copy, " << strlen(s.sptr) + 1 << " Bytes Reallocated And " << strlen(this->sptr) + 1 << " Bytes Freed." << endl;
delete[]sptr;
sptr = new char[strlen(s.sptr) + 1];
strcpy(sptr, s.sptr);
}
void stringCat(const MyString& s)
{
cout << "String Connection, " << strlen(s.sptr) + 1 + strlen(this->sptr) << " Bytes Reallocated And " << strlen(this->sptr) + 1 << " Bytes Freed." << endl;
int m1 = strlen(this->sptr);
int m2 = strlen(s.sptr);
char* temp = new char[m1 + m2 + 1];
strcpy(temp, this->sptr);
strcat(temp, s.sptr);
delete[] sptr;
sptr= new char[m1 + m2 + 1];
strcpy(sptr, temp);
delete[]temp;
}
};