c++面试常见问题之实现一个string类

#include
#include
#include
using namespace std;
class MyString
{

public:
MyString();
MyString(const char* pcStr);
MyString(const MyString& oOther);
~MyString();
MyString& operator=(const MyString& oOther);
MyString operator+(const MyString& oOther);
char operator[](const unsigned int index);
int operator==(const MyString& oOther);
friend ostream& operator<<(ostream& output, const MyString &oOther);
private:
char *m_pcData;

};

//默认的构造函数
MyString::MyString()
{
m_pcData = new char[1];
m_pcData = ‘\0’;
}
//使用const char
来初始化
MyString::MyString(const char* pcStr)
{
if (NULL == pcStr)
{
m_pcData = new char[1];
*m_pcData = ‘\0’;
}
else
{
int ilen = strlen(pcStr);
m_pcData = new char[ilen + 1];
strcpy(m_pcData, pcStr);
}
}
//拷贝构造函数
MyString::MyString(const MyString& oOther)
{
int len = strlen(oOther.m_pcData);
m_pcData = new char[len + 1];
strcpy(m_pcData, oOther.m_pcData);
}

int MyString::operator==(const MyString& oOther)
{
int result = strcmp(m_pcData, oOther.m_pcData);
return result;
}
//赋值操作符
MyString& MyString::operator=(const MyString& oOther)
{
if (this != &oOther)
{

    delete[] m_pcData;
    m_pcData = new char[strlen(oOther.m_pcData) + 1];
    strcpy(m_pcData, oOther.m_pcData);
}
return *this;

}
//重载运算符+
MyString MyString::operator +(const MyString &oOther)
{
MyString newString;
if (!oOther.m_pcData)
newString = this;
else if (!m_pcData)
newString = oOther;
else
{
newString.m_pcData = new char[strlen(m_pcData) + strlen(oOther.m_pcData) + 1];
strcpy(newString.m_pcData, m_pcData);
strcat(newString.m_pcData, oOther.m_pcData);
}
return newString;
}
//重载下标运算符
char MyString::operator [](const unsigned int index)
{
return m_pcData[index];
}
//析构函数
MyString::~MyString()
{
delete[] m_pcData;
}
//重载<<
ostream& operator<<(ostream& output, const MyString &oOther)
{
cout << oOther.m_pcData;
return output;
}
int main()
{
const char
pcStr = “hello,world”;

MyString oString0 = "hello,world";
MyString oString1(pcStr);
MyString oString2 = oString1;
MyString oString3;

oString3 = oString1;
MyString oString4 = oString3 + oString1;
if(0 == (oString1 == oString2))
    cout<<"oString1 == oString2"<

}

你可能感兴趣的:(c++)