1.业务使用main.cpp
#include "pch.h" #include <iostream> int main() { mystring s1;//无参构造函数 mystring s2("s2");//有参构造函数 mystring s3 = s2;//拷贝构造函数 mystring s4 = "s444444444";//有参构造函数 s4 = s2;//mysring& operator=(mysring &s) s4 = "s2222";//mystring& operator=(const char *p) cout << s4[0] << endl;//char& operator[](int index) cout << s4 << endl;//ostream& operator<<(ostream &out, mystring &s) if (s4 == "s2222")//bool operator==(const char *p) { cout << "相等" << endl; } if (s4 != s3)//bool operator==(mystring s) { cout << "不相等" << endl; } //cout << s4.m << endl; std::cout << "Hello World! "; }
2.string.h
#ifndef PCH_H #define PCH_H // TODO: 添加要在此处预编译的标头 #include<iostream> using namespace std; class mystring { friend ostream& operator<<(ostream &out, mystring &s); public: mystring(); mystring(const char *p); mystring(mystring &s); ~mystring(); mystring& operator=(mystring &s); mystring& operator=(const char *p); char& operator[](int index); bool operator==(const char *p) const;//const修饰this的内容不能改变,编译器中默认const mystring *this修饰了this不能指向其他地方 bool operator!=(const char *p) const; bool operator==(mystring s) const; bool operator!=(mystring s) const; protected: int m_len; char *m_p; }; #endif //PCH_H
3.string.cpp
#define _CRT_SECURE_NO_WARNINGS #include "pch.h" // 一般情况下,忽略此文件,但如果你使用的是预编译标头,请保留它。 mystring::mystring() { m_len = 0; m_p = new char[m_len + 1]; strcpy(m_p, ""); } mystring::mystring(const char *p) { if (p == NULL) { m_len = 0; m_p = new char[m_len + 1]; strcpy(m_p, ""); } else { m_len = strlen(p); m_p = new char[m_len + 1]; strcpy(m_p, p); } } // mystring s3 = s2; mystring::mystring(mystring &s) { m_len = s.m_len; m_p = new char[m_len + 1]; strcpy(m_p, s.m_p); } mystring::~mystring() { if (m_p != NULL) { delete m_p; m_p = NULL; m_len = -1; } } //s4 = s2; mystring& mystring::operator=(mystring &s) { //把旧的内存先释放 if (m_p != NULL) { delete[]m_p; m_len = 0; } //根据传进来的参数分配内存 m_len = s.m_len; m_p = new char[m_len + 1]; strcpy(m_p, s.m_p); return *this; } mystring& mystring::operator=(const char *p) { if (m_p != NULL) { delete[]m_p; m_len = 0; } if (p == NULL) { m_len = 0; m_p = new char[m_len + 1]; strcpy(m_p, ""); } else { m_len = strlen(p); m_p = new char[m_len + 1]; strcpy(m_p, p); } return *this; } char& mystring::operator[](int index) { return m_p[index]; } ostream& operator<<(ostream &out, mystring &s) { out << s.m_p; return out; } bool mystring::operator==(const char *p) const { if (p == NULL) { if (m_len == 0) { return true; } } else { if (m_len == strlen(p)) { return !strcmp(m_p, p); } } return false; } bool mystring::operator!=(const char *p) const { return !(*this == p); } bool mystring::operator==(mystring s) const { return !strcmp(m_p, s.m_p); } bool mystring::operator!=(mystring s) const { return !(*this == s); }