實現Stirng類:普通構造、複製構造、賦值函數、重載輸出函數 <<(友元) ios
#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; }