c String類的運算子過載 21

2021-09-07 10:23:45 字數 2348 閱讀 9481

一,建立測試程式包

測試**如下:

/*

date: 2017-5-4

* description: string operator overload test program

* filename: string_operator.h

* author: myron zhou */

#ifndef __string_operator_h_

#define __string_operator_h_ #include

#include

using

namespace

std;

class

mystring

;#endif

/*

date: 2017-5-4

* description: string operator overload test program

* filename: string_operator.cpp

* author: myron zhou */

#include

"string_operator.h

"using

namespace

std;

//預設建構函式,初始化為空串

mystring::mystring()

//建構函式,用乙個字串初始化

mystring::mystring(const

char*str)

//拷貝建構函式,用另外乙個string初始化

mystring::mystring(const mystring&str)

//析構函式

mystring::~mystring()

//過載賦值操作符( = )

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

delete p;

len =str.len;

p = new

char[len + 1

];

strncpy(p, str.p, len + 1

);

return *this

; }

//過載輸出操作符( << )

ostream& operator

<< (ostream& out, const mystring&str)

//過載輸入操作符( >> )

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

//過載加號操作符( + )

mystring operator + (const mystring& str1, const mystring&str2)

//過載相加賦值操作符( += )

mystring operator += (mystring& str1, const mystring&str2)

//過載相等操作符

bool

operator == (const mystring& str1, const mystring&str2)

return

false

; }

//過載不相等操作符

bool

operator != (const mystring& str1, const mystring&str2)

return

true

; }

//過載下標()

char& mystring::operator(int

index)

/*

date: 2017-5-4

* description: string operator overload test program

* filename: main.cpp

* author: myron zhou */

#include

"string_operator.h

"int

main()

二,編譯執行**

運算子過載(實現CString類)

private char m pdate public 建構函式 cstring cstring 拷貝構造 cstring cstring const cstring t cstring if m pdate null deletem pdate m pdate new char strlen t ...

C String類中的運算子過載

模組化設計 標頭檔案 ifndef operator operator h define operator operator h include include using namespace std class mystring endif 功能函式 include operator.h 預設建構...

c String字串類的運算子過載

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