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条评论