1. 程式人生 > >C++ String類過載運算子的實現

C++ String類過載運算子的實現

本篇文章僅供參考,還望各位指出不足,哈哈哈哈

//標頭檔案

#ifndef string_H
#define string_H
#include <assert.h>
using namespace std;
class String
{
friend bool operator==(const String &String1,const String&String2);  //==運算子過載
friend bool operator<(const String&String1, const String&String2);  //<運算子過載函式
friend bool operator>(const String&String1, const String &String2); //>運算子過載函式
private:
char *str;  //定義字串指標
int length;    //字串內容長度
int CharLength; //字串陣列長度
public:
String();
~String()
{
delete[]str;
cout << "析構" << endl;
}
void Show();
void Strlen();//計算字串內容長度

};

#endif // !1



#include<iostream>
#include"String.h"
using namespace std;
#include <assert.h>


String::String()
{
int n;
cout << "請輸入字串的長度:" << endl;
cin >> n;
CharLength = n;
str = new char[CharLength+1];
cout << "請輸入字串內容:" << endl;
cin >> str;
Strlen();
}
bool operator==(const String &String1,const String &String2)
{
int m = 0,i=0;
if (String1.length != String2.length)return false;
while ((String1.str[i] == String2.str[i]) && (String1.str[i] != '\0'))i++;
if (i == String1.length)return true;
else return false;
}
bool operator<(const String&String1, const String&String2)
{
int i = 0;
if (String1.length < String2.length)return true;
while ((String1.str[i] != '\0') && (String2.str[i] != '\0')&&(String1.str[i]==String2.str[i]))
{
i++;
}
if ((String1.str[i] < String2.str[i]) && (String1.str[i] != '\0') && (String2.str[i] != '\0'))return true;
return false;
}
bool operator>(const String&String1, const String&String2)
{
int i = 0;
if (String1.length > String2.length)return true;
while ((String1.str[i] != '\0') && (String2.str[i] != '\0') && (String1.str[i] == String2.str[i]))
{
i++;
}
if ((String1.str[i] > String2.str[i]) && (String1.str[i] != '\0') && (String2.str[i] != '\0'))return true;
return false;
}
void String::Show()
{

cout <<"字串的內容為:"<< str<< endl;
cout << "字串內容的長度為:"<<length << endl;
cout << "字串的長度為:"<<CharLength << endl;
}
void String::Strlen()
{
assert(str);
char *p;
p = str;
int count = 0;
while (*p++) { count++; }
length = count;
}


//測試程式碼


#include<iostream>
#include"string.h"
using namespace std;


int main()
{
cout << "第一個字串:" << endl;
String String1;
cout << "第二個字串" << endl;
String String2;
cout << "String1>String2 is" << endl;
if (String1 > String2)cout<<"true" << endl;
else cout << "false" << endl;
cout << "String1==String2 is" << endl;
if (String1 ==String2)cout << "true" << endl;
else cout << "false" << endl;
cout << "String1<String2 is" << endl;
if (String1 < String2)cout << "true" << endl;
else cout << "false" << endl;


cout << "第一個字串" << endl;
String1.Show();
cout << "第二個字串" << endl;
String2.Show();
system("pause");







return 0;
}