字串類 運算子過載

2021-07-28 01:47:15 字數 1917 閱讀 8729

mystring.h

#define _crt_secure_no_warnings

#includeusing namespace std;

//在這裡定義類只寫類的函式名,不寫類的函式體

//c中沒有字串,字串(c風格字串)

//空串

class mystring

const char *c_str2()

int length()

protected:

private:

int m_len;

char *m_p;

};

mystring.cpp

#include "mystring.h"

mystring::mystring()

mystring::mystring(const char *p )

else }

//拷貝建構函式

//mystring s3 = s2;

mystring::mystring(const mystring& s)

mystring::~mystring()

}mystring& mystring::operator=(const char *p)

//根據p分配記憶體

if (p == null)

else

return *this;

}//原型2 //s4 = s2;

mystring& mystring::operator=(const mystring &s)

//根據s分配記憶體

m_len = s.m_len;

m_p = new char[m_len + 1];

strcpy(m_p ,s.m_p);

return *this;

}ostream& operator<<(ostream &out,mystring &s)

else

}}bool mystring::operator!=(const char *p) const

bool mystring::operator==(const mystring& s) const

if (strcmp(m_p,s.m_p)) }

bool mystring::operator!=(const mystring& s) const

//過載 < >

//if (s3 < "bbbb")

int mystring::operator<(const char *p)

int mystring::operator>(const char *p)

int mystring::operator<(const mystring& s)

int mystring::operator>(const mystring& s)

istream& operator>>(istream &in ,mystring &s)

mystring_test.cpp

#includeusing namespace std;

#include "mystring.h"

int main01()

else /*

if (s3 < s2)

else

*//*

mystring s4 = "aaaaffff";

strcmp(s4.c_str(),"aa111");

cout<>s1;

//// //istream& operator>>(istream &in ,mystring &s);

// // system("pause");

// return 0;

//}

c String字串類的運算子過載

在c 中有乙個新定義的型別string,可以不用那麼麻煩的操作字串,並且一些高階的運算子過載讓她的使用更加便捷 下面是string類的定義和成員函式的定義 ifndef operator operator h define operator operator h include includeusi...

字串類中的運算子過載

ifndef string h define string h include using namespace std class string endif include string.h include include include using namespace std string str...

類方法用字串實現運算子的過載

運算子的過載 對已有的運算子重新進行定義,賦予其另一種功能,以適應不同的資料型別。本 實現的成員函式有建構函式 拷貝建構函式 運算子 運算子 類內實現物件加物件,物件加字串,類外實現字串加物件 析構函式 運算子 運算子 運算子 輸出符 類外實現 兩個類外實現的函式用了友元函式,類內由於有this指標...