Implementation of the String class

Source: Internet
Author: User

# Include <cstdlib> # include <string. h ># include <iostream> using namespace std; class String {public: String (const char * str = NULL); // common const String (const String & other ); // copy the constructor ~ String (); // analysis function String & operator = (const String & other); friend ostream & operator <(ostream & OS, const String & s); private: char * data; // used to save the data String}; ostream & operator <(ostream & OS, const String & s) {int len = strlen (s. data); for (int I = 0; I <len; I ++) {OS <s. data [I];} return OS;} String: String (const char * str) {if (str = NULL) {data = new char [1]; if (data! = NULL) data = '\ 0';} else {int len = strlen (str); data = new char [len + 1]; if (data! = NULL) strcpy (data, str) ;}} String: String (const String & other) {int len = strlen (other. data); data = new char [len + 1]; if (data! = NULL) strcpy (data, other. data);} String ::~ String () {delete [] data;} String & String: operator = (const String & other) {if (this = & other) return * this; delete [] data; data = NULL; int len = strlen (other. data); data = new char [len + 1]; if (data! = NULL) strcpy (data, other. data); return * this ;} ######################################## ######################################## ######## int main (void) {String s1 ("string"); String s2 (s1); cout <"s1:" <s1 <endl; cout <"s2: "<s2 <endl; return 0 ;}


This article is from the "to simplicity" blog, please be sure to keep this source http://zhijian.blog.51cto.com/2057586/1268995

Related Article

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.