C + + implements the String class

Source: Internet
Author: User

1#include <iostream>2#include <cstring>3 using namespacestd;4 classString {5  Public:6String (Const Char* str =NULL) {7M_STR =New Char[Strlen (STR?STR:"")+1];8strcpy (M_STR, str. STR:"");9     }Ten~string (void) { One         if(m_str) { A             Delete[] m_str; -M_STR =NULL; -         } the     } -String (Conststring&that): - m_str (strcpy ( -             New Char[Strlen (THAT.M_STR) +1], + that.m_str)) {} -     /*Rookie + void operator= (const string& that) { A m_str = new Char[strlen (THAT.M_STR) +1]; at strcpy (m_str, that.m_str); -     }*/ -string&operator= (Conststring&That ) { -         if(&that! = This) { -             /*Bird - delete[] m_str; in m_str = new Char[strlen (THAT.M_STR) +1]; - strcpy (m_str, that.m_str); to             */ +             /*Big Bird - char* str = the new Char[strlen (THAT.M_STR) +1]; * delete[] m_str; $ m_str = strcpy (str, that.m_str);Panax Notoginseng             */ -             //Veteran the String Temp (that); + swap (m_str, temp.m_str); A         } the         return* This; +     } -     Const Char* C_STR (void)Const { $         returnm_str; $     } -     operator Const Char* (void)Const { -         returnc_str (); the     } - Private:Wuyi     Char*m_str; the }; - intMain (void) { WuString S1 ("Hello, World!"); -cout << s1.c_str () <<Endl; AboutString s2 =S1; $cout << s2.c_str () <<Endl; -String S3 ("Hello, Linux!"); -     Try { -S1 =S3; A     } +     Catch(exception&ex) { thecout << ex.what () <<Endl; -     } $cout << s1.c_str () <<Endl; the     Const Char* Psz =S1; thecout << S1 <<Endl; thecout << psz <<Endl; the     return 0; -}

C + + implements the String class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.