String 类的简单技巧实现

来源:互联网 发布:淘宝代销怎么刷销量 编辑:程序博客网 时间:2024/04/30 03:16
#include <iostream>using namespace std;class MyString{public:MyString(const char* str = NULL);MyString(const MyString &other);~MyString();MyString& operator = (const MyString& other);friend ostream& operator <<(ostream& os, const MyString& other);/*<<有两个参数,一个是输出流对象(我们常用的cout),还有就是要输出的东西。例如:cout<<"haha";也就是说<<的第一个参数必须是输出流对象。在成员函数里实现<<重载,我们知道this会作为第一个参数,而这是不符合要求的。>>类似!*/friend istream& operator >>(istream& is, MyString& other);private:char *m_data;};MyString::MyString(const char* str){if(str == NULL){m_data = new char[1];*m_data = '\0';}else{int len = strlen(str);m_data  = new char[len + 1];strcpy(m_data, str);}}MyString::MyString(const MyString &other){int len = strlen(other.m_data);m_data  = new char[len + 1];strcpy(m_data, other.m_data);}MyString::~MyString(){delete[] m_data;}MyString& MyString::operator = (const MyString& other){if(this == &other){return *this;}else{delete[] m_data;m_data = new char[strlen(other.m_data) + 1];strcpy(m_data, other.m_data);return *this;}}ostream& operator <<(ostream& os, const MyString& other){os << other.m_data;return os;}istream& operator >> (istream& is, MyString& other)  {  const int limit_string_size = 4096;other.m_data = new char[limit_string_size];is >> other.m_data;return is;}int main(){MyString str,str1;cin>>str;cout<<str<<endl;str1 = str;cout<<str1;return 0;}

原创粉丝点击