String类的实现

#include 
#include 
#include 
using namespace std;
class String
{
    friend std::ostream& operator << (std::ostream& os, const String& str);
private:
    char* Data;		//私有变量来保存字符串
public:
    String(const char* str = NULL);		//构造函数
    String(const String& str);			//拷贝构造函数
    ~String();							//析构函数
    String& operator =(const String& str);		//赋值运算符
    String operator +(const String& str);		//字符串连接
    bool operator ==(const String& str);		//判断是否相等
    char operator [](int index);				//数组的索引
    int GetLength();							//字符串长度
};
//构造函数
String::String(const char* str)
{
    if (str == NULL)
    {
	this->Data = NULL;
    }
    else
    {
	this->Data = new char[strlen(str) + 1];
	strcpy(this->Data, str);
    }
}
//拷贝构造函数
String::String(const String& str)
{
    if (str.Data == NULL)
    {
	this->Data = NULL;
    }
    else
    {
	this->Data = new char[strlen(str.Data) + 1];
	strcpy(this->Data, str.Data);
    }
}
//析构函数
String::~String()
{
    if (this->Data)
    {
	delete[] this->Data;
	this->Data = NULL;
    }
}
//赋值运算符
String& String::operator =(const String& str)
{
    if (this != &str)
    {
	delete[] this->Data;
	if (!str.Data)
	{
	    this->Data = 0;
	}
	else
	{
	    this->Data = new char[strlen(str.Data) + 1];
	    strcpy(this->Data, str.Data);
	}
    }
    return *this;
}
//字符串连接
String String::operator +(const String& str)
{
    String newstr;
    if (!str.Data)
    {
        newstr = *this;
    }
    else if (!this->Data)
    {
        newstr = str;
    }
    else
    {
	newstr.Data = new char[strlen(this->Data) + strlen(str.Data) + 1];
	strcpy(newstr.Data, this->Data);
	strcat(newstr.Data, str.Data);
    }
    return newstr;
}
//判断是否相等
bool String::operator ==(const String& str)
    {
    if (strlen(this->Data) != strlen(str.Data))
    {
	return false;
    }
    else
    {
	return strcmp(this->Data, str.Data) ? false : true;
    }
}
//数组下标
char String::operator [](int index)
{
    if (index > 0 && index < (int)strlen(this->Data))
    {
	return this->Data[index];
    }
    return 0;
}
//字符串长度
int String::GetLength()
{
    return strlen(this->Data);
}
//输出运算符重载
std::ostream& operator <<(std::ostream& os, const String& str)
{
    os << str.Data;
    return os;
}
int main()
{
    String str1("Hello World !");
    String str2("Hello String !");
    cout << "str1:" << str1 << endl;
    cout << "str2:" << str2 << endl;
    String str3 = str1 + str2;
    cout << "str3:" << str3 << endl;
    String str4 = str2;
    str1 = str2;
    cout << "str4:" << str4 << endl;
    cout << "str1:" << str1 << endl;
    cout << "str3's length:" << str3.GetLength() << endl;
    cout << "str3[4]:" << str3[4] << endl;
    cout << (str1 == str3) << endl;
    return 0;
} 

 

你可能感兴趣的:(C++)