#ifndef STRING_H #define STRING_H #include <iostream> using namespace std; class String { public: /*explicit*/ String(const char* str = ""); // 防止转换构造函数 String s = "XXX"; 情况 String(const String& other); ~String(); String& operator =(const String& other); String& operator =(const char* str); bool operator !() const; // 如果该字符串的长度为0,那么!就返回真 char& operator [](unsigned int index); // 返回引用指向实际的空间,可以出现在等号的左边,s[2] = 'c'; const char& operator [](unsigned int index) const; // 应该使用非const 函数调用const函数,避免代码重复 String& operator +=(const String& s); friend String operator +(const String& s1, const String& s2); friend ostream& operator <<(ostream&os, const String& s); // 流运算符的重载只能使用友元的方式重载,因为第一个参数是是流变量 friend istream& operator >>(istream&is, String& s); // 重载 void Display() const; private: String& Assign(const char* str); char* AllocAndCopy(const char* str); // 拷贝,分配字符串空间 char* str_; }; #endif // STRING_H
#include "string.h" #include <string.h> // 构造函数 String::String(const char* str) { this->str_ = this->AllocAndCopy(str); } // 一个参数的构造函数,充当构造函数和拷贝构造函数 String::String(const String &other) { this->str_ = this->AllocAndCopy(other.str_); } // 析构函数 String::~String() { delete[] this->str_; } // 分配内存,拷贝字符串 char* String::AllocAndCopy(const char *str) { int length = strlen(str) + 1; char* tmp = new char[length]; memset(tmp, 0, length); strcpy(tmp, str); return tmp; } // 重载等号运算符 String& String::operator =(const String& other) { if (this == &other) return *this; return this->Assign(other.str_); } String& String::operator =(const char* str) { return this->Assign(str); } String& String::Assign(const char *str) { delete[] this->str_; this->str_ = this->AllocAndCopy(str); return *this; } bool String::operator !() const { return (strlen(this->str_) != 0); } char& String::operator [](unsigned int index) { // return this->str_[index]; return const_cast<char&>(static_cast<const String&>(*this)[index]); } const char& String::operator [](unsigned int index) const { return this->str_[index]; } String operator +(const String& s1, const String& s2) { /* int length = strlen(s1.str_) + strlen(s2.str_) + 1; char* tmpStr = new char[length]; memset(tmpStr, 0, length); strcpy(tmpStr, s1.str_); strcat(tmpStr, s2.str_); String tmpString(tmpStr); delete tmpStr; return tmpString; */ String tmpString = s1; tmpString += s2; return tmpString; } String& String::operator +=(const String& other) { int length = strlen(this->str_) + strlen(other.str_) + 1; char* tmpStr = new char[length]; memset(tmpStr, 0, length); strcpy(tmpStr, this->str_); strcat(tmpStr, other.str_); delete[] this->str_; this->str_ = tmpStr; return *this; } void String::Display() const { cout << this->str_ << endl; } ostream& operator <<(ostream&os, const String& s) { os<<s.str_; return os; } istream& operator >>(istream&is, String& s) { /* is>>s.str_; return is; */ char tmp[1024]; cin >> tmp; s.str_ = tmp; return is; }