题目: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_; } 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; }
#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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u013507368/article/details/48111607