c++实现 String 类
实现Stirng类:普通构造、复制构造、赋值函数、重载输出函数 <<(友元)
#include <iostream> #include <string.h> #include <stdlib.h> using namespace std; class String { public: String (const char *str=NULL); //普通构造函数 String (const String &other); //复制构造函数 ~String (void); //析构函数 String &operator=(const String &other); //赋值函数 friend ostream &operator<<(ostream &output, const String &other); //输出函数 private: char *data; //保存字符串 }; //普通构造函数 String::String(const char *str) { if (str == NULL) { data = new char[1]; *data = '\0'; } else { int len = strlen(str); data = new char[len+1]; strcpy(data, str); } } //复制构造函数 String::String(const String &other) { int len = strlen(other.data); data = new char[len+1]; strcpy(data, other.data); } //析构函数 String::~String() { delete[] data; } //赋值函数 String &String::operator=(const String &other) { if (this == &other) { return *this; } delete[] data; int len = strlen(other.data); data = new char[len+1]; strcpy(data, other.data); return *this; } //输出函数 ostream &operator<<(ostream &output, const String &other) { output<<other.data; return output; } int main() { String s1("hello"); cout << s1 << endl; String s2=s1; cout << s2 << endl; String s3; s3=s1; cout << s3 << endl; }