字串類中的運算子過載

2021-08-18 07:01:14 字數 2324 閱讀 9927

#ifndef _string_h_

#define _string_h_

#include

using namespace std;

class string

;#endif

#include "string.h"

#include

#include

#include

using namespace std;

string::string()

string::string(char *str)

string::string(int l,char ch)

m_ptr[m_length] = '\0';

}string::string(const string &s)

string::~string()

}//過載"<<"運算子

ostream &operator <<(ostream &out,const string &s)

//過載">>"運算子

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

//過載"="運算子

string &string::operator =(const string &s1)

if(m_ptr != null)

if(s1.m_ptr)

else

return *this;

}string &string::operator =(char *p)

m_length = strlen(p);

m_ptr = new char(m_length + 1);

strcpy(m_ptr,p);

m_ptr[m_length] = '\0';*/

*this = string(p);

return *this;

}//過載""運算子

char &string::operator (int index)

return m_ptr[index];

}//過載"+"運算子

string string::operator +(const string &s)

else

return t;

}string string::operator +(char *p)

else

return t;

/*cout << "111" << endl;

string t(p);

cout << "222" << endl;

t = *this + t;

cout << "333" << endl;

return t;*/

}//過載"+="運算子

string string::operator +=(const string &s)

else

return t;*/

cout << "111" << endl;

char *temp = m_ptr;

m_ptr = new char[strlen(temp) + strlen(s.m_ptr) + 1];

strcpy(m_ptr,temp);

strcat(m_ptr,s.m_ptr);

delete temp;

cout << "111" << endl;

return *this;

}string string::operator +=(char *p)

//過載"=="運算子

int string::operator ==(const string &s)

/*string &string::operator ==(char *p)

*///過載"!="運算子

int string::operator !=(const string &s)

/*char &string::operator !=(char *p)

*///過載"<"運算子

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

//過載">"運算子

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

#include "string.h"

#include

using namespace std;

int main(int argc, char **argv)

else

if(s1 != s2)

if(s1 < s2)

if(s1 > s2)

return 0;

}

字串類 運算子過載

mystring.h define crt secure no warnings includeusing namespace std 在這裡定義類只寫類的函式名,不寫類的函式體 c中沒有字串,字串 c風格字串 空串 class mystring const char c str2 int leng...

c String字串類的運算子過載

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

C 字串中運算子的過載問題

運算子的過載 運算子的過載實際是一種特殊的函式過載,必須定義乙個函式,並告訴c 編譯器,當遇到該過載的運算子時呼叫此函式。這個函式叫做運算子過載函式,通常為類的成員函式。定義運算子過載函式的一般格式 返回值型別 類名 operator過載的運算子 參數列 在字串中,運算子的過載問題在於字串和字串之間...