string.h
#include
#include
using
namespace std;
class
string
;
string.cpp
#include
"string.h"
string::
string()
//預設建構函式,構造空字串
string::
string
(int n,
char c)
//普通建構函式
*temp =
'\0';}
string::
string
(const
char
* source)
//普通建構函式
else
}string::
string
(const string& s)
//複製建構函式
string& string::
operator=(
char
* s)
// = 過載
size =
strlen
(s);
data =
newchar
[size +1]
;strcpy
(data, s)
;return
*this
;//複製目標字串
}string& string::
operator=(
const string& s)
// = 過載
if(data !=
null
)//釋放data堆記憶體
size =
strlen
(s.data)
; data =
newchar
[size +1]
;//分配堆記憶體
strcpy
(data, s.data)
;//複製物件s的字串成員
return
*this;}
string::
~string()
}char
& string::
operator
(int i)
// 過載
const
char
& string::
operator
(int i)
const
// 過載
string& string::
operator+=
(const string& s)
//+=過載
string& string::
operator+=
(const
char
* s)
//過載+=
int string::
length()
ostream&
operator
<<
(ostream& out, string &s)
//過載<<
return out;
}istream&
operator
>>
(istream& in, string& s)
bool
operator
<
(const string& left,
const string& right)
//過載<
return left[i]
- right[i]
<0?
true
:false
;//return strcmp(left.data, right.data) < 0;
}bool
operator
>
(const string& left,
const string& right)
//過載》
return left[i]
- right[i]
>0?
true
:false
;//return strcmp(left.data, right.data) > 0;
}bool
operator==(
const string& left,
const string& right)
//過載==
else
return
false;}
return
true
;//return strcmp(left.data, right.data) == 0;
}bool
operator!=(
const string& left,
const string& right)
//過載!=
else
}return
false
;//return strcmp(left.data, right.data) != 0;
}
main.cpp
#include
#include
"string.h"
using
namespace std;
intmain()
c 實現的string類
普通版 class string else 拷貝建構函式 string const string str 引數為引用,如果為值的話 可能無限呼叫拷貝構造陷入死迴圈 pstr new char strlen str.pstr 1 賦值過載函式 string operator const string ...
模擬實現string類 c
include include using namespace std class string string const string m 拷貝建構函式 string 析構函式 string operator string m1 賦值運算子過載 s new char strlen m1.s 1 s...
C 中String類的實現
include include using namespace std class string else 拷貝建構函式 開闢跟源字串長度一樣長的空間給目標物件 string string s pstr new char strlen s.pstr 1 賦值運算子的過載 因為考慮到連續賦值的情況,故...