2 回答
TA贡献1993条经验 获得超5个赞
#include <iostream>
#include <cstring>
using namespace std;class MyString
{
public:
MyString();
MyString(char*);
MyString(const MyString&);
~MyString();
size_t length();
size_t size();
char at(unsigned);
MyString& operator =(const MyString&);
void print();
friend MyString operator +(const MyString&, const MyString&);
private:
char* szBuf;
size_t stSize;
size_t stLen;
};MyString::MyString(): stSize(256), stLen(0)
{
cout << "调用无参构造函数" << endl;
szBuf = new char[stSize];
}MyString::MyString(char* buf): stSize(256)
{
cout << "调用参数为字符指针的构造函数" << endl;
if (stSize-1 < strlen(buf))
{
stSize = strlen(buf) + 1;
}
szBuf = new char[stSize];
strcpy(szBuf, buf);
stLen = strlen(szBuf);
}MyString::MyString(const MyString& str): stSize(256)
{
cout << "调用拷贝构造函数" << endl;
if (stSize-1 < str.stLen)
{
stSize = str.stLen + 1;
}
szBuf = new char[stSize];
strcpy(szBuf, str.szBuf);
stLen = strlen(szBuf);
}MyString::~MyString()
{
cout << "调用析构函数" <<endl;
if (szBuf != NULL)
{
delete[] szBuf;
}
}size_t MyString::length()
{
return stLen;
}size_t MyString::size()
{
return stSize;
}char MyString::at(unsigned index)
{
if ((szBuf != NULL) && (index < stLen))
{
return szBuf[index];
}
return 0;
}MyString& MyString::operator=(const MyString& str)
{
if (stSize < str.stLen + 1)
{
delete[] szBuf;
stSize = str.stLen + 1;
szBuf = new char[stSize];
}
memset(szBuf, 0, stSize);
strcpy(szBuf, str.szBuf);
return *this;
}void MyString::print()
{
cout << this->szBuf;
}MyString operator+(const MyString& str1, const MyString& str2)
{
char *buf;
int len;
len = str1.stLen + str2.stLen + 1;
buf = new char[len];
strcpy(buf, str1.szBuf);
strcat(buf, str2.szBuf);
MyString str(buf);
delete[] buf;
return str;
}int main()
{
MyString* str1;
str1 = new MyString("abcdefe");
str1->print();
cout << endl;
MyString str2(*str1);
str2 = *str1 + str2;
cout << endl;
str2.print();
cout << endl;
for (int i = 0; i < str1->length(); i++)
{
cout << str1->at(i);
}
cout << endl;
delete str1;
return 0;
}
添加回答
举报