C++ 字串重載運算子

來源:互聯網
上載者:User

標籤:

#include<iostream.h>#include<string.h>//using namespace std;class Cstring{public:Cstring(){p = new char[1];*p = '\0';}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 &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 &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);delete[]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>s2)<<endl;cout <<(s1<s2)<<endl;s3 = s1;s3.Show();s3 = s1+s2;s3.Show();}


在VC6.0下如果將標頭檔改為:

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

就會出現下列錯誤

error C2248: ‘p‘ : cannot access private member declared in class ‘Cstring‘

C++ 字串重載運算子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.