題目:string類的簡單實現,本文中此類名爲MyString
實現思路:
1 只要構造函數執行成功(其中pData_不爲空)
2 構造函數可通過char*,字符串常量構造
3 重載運算符=(返回值爲MyString),實現拷貝構造函數(深拷貝,返回值爲MyString&)
4 重載運算符<<,使之可通過cout輸出
5 實現字符串長度,字符串是否爲空函數
6 成員變量使用char* pData_保存字符串,使用int length_保存字符串長度
MyString.h
#pragma once
#include <iostream>
class MyString
{
public:
MyString(const char * pStr = nullptr);
MyString(const MyString& rhs);
~MyString();
bool empty();
MyString& operator=(const MyString& rhs);
MyString operator+(const MyString& rhs);
size_t size()
{
return length_;
}
friend std::ostream& operator<<(std::ostream& os, const MyString &rhs);
private:
char *pData_;
size_t length_;
};
std::ostream& operator<<(std::ostream& os, const MyString &rhs);
#include "MyString.h"
#include <cstring>
MyString::MyString(const char *pStr)
{
if (nullptr == pStr)
{
pData_ = new char[1];
*pData_ = '\0';
length_ = 0;
}
else
{
length_ = strlen(pStr);
pData_ = new char[length_ + 1];
strcpy(pData_, pStr);
}
}
MyString::~MyString()
{
if (nullptr != pData_)
{
delete pData_;
pData_ = nullptr;
length_ = 0;
}
}
MyString::MyString(const MyString& rhs)
{
if (nullptr == rhs.pData_)
{
pData_ = new char[1];
*pData_ = '\0';
length_ = 0;
}
else
{
length_ = rhs.length_;
pData_ = new char[length_ + 1];
strcpy(pData_, rhs.pData_);
}
}
MyString& MyString::operator=(const MyString& rhs)
{
if (this == &rhs)
{
return *this;
}
MyString newString(rhs);
char*temp = newString.pData_;
newString.pData_ = pData_;
pData_ = temp;
length_ = rhs.length_;
</pre><pre code_snippet_id="1557082" snippet_file_name="blog_20160115_4_9550508" name="code" class="cpp"><span style="white-space:pre"> </span>return *this;
}
MyString MyString::operator+(const MyString& rhs)
{
MyString newString;
if (length_ > 0 || rhs.length_ > 0)
{
char* temp = new char[length_ + rhs.length_ + 1];
strcpy(temp, pData_);
strcat(temp, rhs.pData_);
delete newString.pData_;
newString.pData_ = temp;
newString.length_ = length_ + rhs.length_;
}
return newString;
}
bool MyString::empty()
{
if (size() > 0)
{
return false;
}
else
{
return true;
}
}
std::ostream& operator<<(std::ostream& os, const MyString &rhs)
{
os << rhs.pData_;
return os;
}
main.cpp 測試代碼
#include <iostream>
#include "MyString.h"
using namespace std;
int main()
{
MyString str;
cout << "str = "<< str << endl;
if (str.empty())
{
cout << "str is empty" << endl;
}
else
{
cout << "str is not empty" << endl;
}
str = "fivestar";
cout << "str = " << str << endl;
if (str.empty())
{
cout << "str is empty" << endl;
}
else
{
cout << "str is not empty" << endl;
}
MyString str2 = " love a lot of girls";
cout <<"str2.size() = "<< str2.size() << endl;
cout << str + str2 << endl;
return 0;
}