C++字符串处理操作符重载
生活随笔
收集整理的這篇文章主要介紹了
C++字符串处理操作符重载
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
&& || 不能進(jìn)行運算符重載,因為運算符重載不能進(jìn)行截斷操作
截斷操作就是當(dāng) a || b,a為真的時候就不會再判斷b了,但是運算符重載不能達(dá)到這效果。
類定義
// 類定義#include <iostream> using namespace std;//c中沒有字符串 字符串類(c風(fēng)格的字符串) //空串 "" class MyString {friend ostream& operator<<(ostream &out, MyString &s);friend istream& operator>>(istream &in, MyString &s); public:MyString(int len = 0);MyString(const char *p);MyString(const MyString& s);~MyString();public: //重載=號操作符MyString& operator=(const char *p);MyString& operator=(const MyString &s);char& operator[] (int index);public: //重載 == !== bool operator==(const char *p) const;bool operator==(const MyString& s) const;bool operator!=(const char *p) const;bool operator!=(const MyString& s) const;public:int operator<(const char *p);int operator>(const char *p);int operator<(const MyString& s);int operator>(const MyString& s);//把類的指針 露出來 public:char *c_str(){return m_p;}const char *c_str2(){return m_p;}int length(){return m_len;} private:int m_len;char *m_p;};- << 和 >> 操作符重載
- copy構(gòu)造函數(shù)
- =運算符重載
[]運算符重載
char& MyString::operator[](int index) {return m_p[index]; }== 和 !=運算符重載
//if (s2 == "s222222") bool MyString::operator==(const char *p) const {if (p == NULL){if (m_len == 0){return true;}else{return false;}}else{if (m_len == strlen(p)){return !strcmp(m_p, p);}else{return false;}} }bool MyString::operator!=(const char *p) const {return !(*this == p); }bool MyString::operator==(const MyString& s) const {if (m_len != s.m_len){return false;}return !strcmp(m_p, s.m_p); }bool MyString::operator!=(const MyString& s) const {return !(*this == s); }> 和<操作符重載
//if (s3 < "bbbb") int MyString::operator<(const char *p) {return strcmp(this->m_p , p); }int MyString::operator>(const char *p) {return strcmp(p, this->m_p); }int MyString::operator<(const MyString& s) {return strcmp(this->m_p , s.m_p); }int MyString::operator>(const MyString& s) {return strcmp(s.m_p, m_p); }總結(jié)
以上是生活随笔為你收集整理的C++字符串处理操作符重载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于炼铁大数据智能互联平台推动传统工业转
- 下一篇: s3c2440移植MQTT