//MyString.h #pragma once #include <iostream> using namespace std; class MyString { private: char *m_ptr;//内存空间 public: MyString(const char *str=NULL);//构造函数 MyString(const MyString& obj); //拷贝构造函数 ~MyString(); //析构函数 public: // + = > < == != >> << MyString operator+(const MyString& obj); //连接 MyString &operator=(const MyString& obj); //赋值 bool operator>(const MyString& obj); //比较大小 bool operator<(const MyString& obj); //比较大小 bool operator==(const MyString& obj); //比较大小 bool operator!=(const MyString& obj); //比较大小 friend istream& operator>>(istream& in, MyString &obj); //输入流 friend ostream& operator<<(ostream& out, const MyString& obj); //输出流 };
//MyString.cpp #define _CRT_SECURE_NO_WARNINGS #include "MyString.h" MyString::MyString(const char *str)//构造函数 { if (str == NULL) { this->m_ptr = new char[1]; this->m_ptr[0] = '\0'; } else { this->m_ptr = new char[strlen(str)+1]; strcpy(this->m_ptr, str); } } MyString::MyString(const MyString& obj) //拷贝构造函数 { this->m_ptr = new char[strlen(obj.m_ptr) + 1]; strcpy(this->m_ptr, obj.m_ptr); } MyString::~MyString() //析构函数 { delete[] m_ptr; this->m_ptr = NULL; } MyString MyString::operator+(const MyString& obj) //连接 { MyString tmp; delete[] tmp.m_ptr; tmp.m_ptr = new char[strlen(this->m_ptr) + strlen(obj.m_ptr) + 1]; sprintf(tmp.m_ptr, "%s%s", this->m_ptr, obj.m_ptr); return tmp; } MyString &MyString::operator=(const MyString& obj) //赋值 { if (this->m_ptr != NULL) { delete[] m_ptr; this->m_ptr = NULL; } this->m_ptr = new char[strlen(obj.m_ptr) + 1]; strcpy(this->m_ptr, obj.m_ptr); return *this; } bool MyString::operator>(const MyString& obj) //比较大小 { if (-1 == strcmp(this->m_ptr, obj.m_ptr)) { return true; } else { return false; } } bool MyString::operator<(const MyString& obj) //比较大小 { if (1 == strcmp(this->m_ptr, obj.m_ptr)) { return true; } else { return false; } } bool MyString::operator==(const MyString& obj) //比较大小 { if (0 == strcmp(this->m_ptr, obj.m_ptr)) { return true; } else { return false; } } bool MyString::operator!=(const MyString& obj) //比较大小 { return !(*this==obj); } ostream& operator<<(ostream& out, const MyString& obj) //输出流 { out << obj.m_ptr; return out; } istream& operator>>(istream& in, MyString &obj) //输入流 { char tmp[1024 * 10]; memset(tmp, 0, sizeof(tmp)); in >> tmp; if (obj.m_ptr != NULL) { delete[] obj.m_ptr; obj.m_ptr = NULL; } obj.m_ptr = new char[strlen(tmp) + 1]; strcpy(obj.m_ptr, tmp); return in; }
//MyStringTest.cpp #include "MyString.h" using namespace std; void run() { MyString s1("abd"); MyString s2("hello"); MyString s3 = s2; MyString s4; //s1 = s2; s4 = s1 + s2; cout << s4 << endl; if (s1==s2) { cout << "相等" << endl; } else { cout << "不相等" << endl; if (s1 < s2) { cout << "s1<s2" << endl; } else if (s1 > s2) { cout << "s1>s2" << endl; } } cout << s1 <<","<< s2 << endl; cin >> s4; cout << s4 << endl; } void main() { run(); system("pause"); }
时间: 2024-09-11 08:42:20