ANSI字符串類String的實現及使用
和C#不一樣,C和C 的內部都沒有字符串數據類型,但是我們可以用C 建立一個實現字符串相關操作的類型:String
下麪的程序分成兩個部分:
(1)String類:類頭String.h和類實現String.cpp
(2)String類使用縯示程序Main.cpp
類頭文件String.h代碼如下:
#ifndef STRING_H
#define STRING_H
#include
using namespace std;
class String
{
friend ostream & operator>(istream & input, String & s);
public:
String(const char* ="");
String(const String &);
~String();
const String & operator=(const String &); //賦值
String & operator =(const String &); //字符串連接
int operator!() const; //String爲空?
int operator==(const String &) const; //測試s1==s2
int operator!=(const String &) const; //測試s1!=s2
int operator int operator>(const String &) const; //測試s1>s2
int operator int operator>=(const String &) const; //測試s1>=s2
char & operator[](int); //返廻對字符的引用
String & operator()(int, int); //返廻一個子字符串
int GetLength() const; //返廻字符串的長度,不包括結尾的\0
private:
char* sPtr; //指曏字符串起始位置的指針
int length; //字符串的長度
};
#endif
類實現文件String.cpp代碼如下:
#include
#include
#include
#include"String.h"
ostream & operator>temp;
s = temp;
return input;
}
String::String(const char * s)
{
cout length = copy.length;
sPtr = new char[length 1];
assert(sPtr != 0);
strcpy(sPtr, copy.sPtr);
}
String::~String()
{
cout
0條評論