C + + string overloading operator

Source: Internet
Author: User

#include <iostream.h> #include <string.h>//using namespace Std;class cstring{public:cstring () {p = new char[ 1];*p = ' + ';} Cstring (const char *t); Cstring (const Cstring &t); ~cstring () {delete[]p;} BOOL operator< (const Cstring &t) const;friend bool operator > (const Cstring &str1,const Cstring &AMP;STR2); cstring& operator= (const Cstring &t); Cstring operator+ (const Cstring &t) Const;bool operator== (const Cstring &t) const;char& operator[] (int index ); void Show () {Cout<<p<<endl;} Private:char *p;}; cstring::cstring (const char *t) {if (t = = NULL) T = ""; int n = strlen (t);p = new char[n+1];strcpy (p,t);} cstring::cstring (const Cstring &t) {p = new Char[strlen (T.P) +1];strcpy (P,T.P);}                                                BOOL Cstring::operator < (const Cstring &t) const{if (strcmp (P, T.P) < 0) return true; else return false;} BOOL operator > (const Cstring &str1, const Cstring &AMP;STR2) {if (strcmp (STR1.P, STR2.P) > 0) retUrn true; else return false;} BOOL Cstring::operator = = (Const Cstring &t) Const{return strcmp (p,t.p) = = 0;} char& Cstring::operator [] (int index) {return p[index];} Cstring Cstring::operator + (const Cstring &t) Const{char *pt;pt = new Char[strlen (p) +strlen (T.P) +1];strcpy (pt,p); strcat (PT,T.P); Cstring Temp (PT);d Elete[]pt;return temp;} cstring& Cstring::operator = (const Cstring &t) {if (this = = &t) return *this;delete[]p;p = new Char[strlen (T.P) +1];strcpy (P,T.P); return *this;} void Main () {Cstring S1 ("Hello"); Cstring S2 ("World"); Cstring s3;s1. Show ()//if (s1[0]>= ' A ' &&s1[0]<= ' Z ')//s1[0] = s1[0]+32;//S1. Show (); cout << (S1&GT;S2) <<endl;cout << (s1<s2) <<endl;s3 = S1;s3. Show (); s3 = S1+s2;s3. Show ();}


Under VC6.0, if you change the header file to:

#include <iostream>
#include <string.h>
using namespace Std;

The following error will occur

Error C2248: ' P ': cannot access private member declared in class ' Cstring '

C + + string overloading operator

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.