#include <cstdlib> #include <string.h> #include <iostream> using namespace std; class String { public: String(const char *str = NULL);//普通構造函數 String(const String &other);//拷貝構造函數 ~String();//析夠函數 String& operator =( const String &other); friend ostream& operator<<(ostream& os, const String & s); private: char *data ;//用於保存數據字符串 }; ostream& operator<<(ostream& os,const String& s) { int len = strlen(s.data ); for(int i=0;i<len;i++) { os<<s. data[i]; } return os; } String::String( const char *str) { if(str == NULL) { data = new char[1]; if(data != NULL) data = '\0' ; } else { int len = strlen(str); data = new char[len+1]; if(data != NULL) strcpy( data,str); } } String::String( const String &other) { int len = strlen(other.data ); data = new char[len+1]; if(data != NULL) strcpy( data,other.data ); } String::~String() { delete [] data ; } String& String::operator=( const String &other) { if(this == &other) return *this ; delete [] data ; data = NULL; int len = strlen(other.data ); data = new char[len+1]; if(data != NULL) strcpy( data,other.data ); return *this ; } ######################################################################################## int main( void) { String s1("string" ); String s2(s1); cout<< "s1:"<<s1<<endl; cout<< "s2:"<<s2<<endl; return 0; }
本文出自 “至簡” 博客,請務必保留此出處http://zhijian.blog.51cto.com/2057586/1268995