编写String 类的构造函数,析构函数和赋值函数

来源:互联网 发布:偏头痛物理疗法知乎 编辑:程序博客网 时间:2024/06/06 16:27
//.......................编写String 类的构造函数,析构函数和赋值函数#if 0#include<iostream>#include<string>using namespace std;class String { friend ostream & operator<<(ostream& o,const String &str);  public:String(const char *str = NULL); //普通构造函数String(const String &other);  //复制构造函数~String(void);  //析构函数String & operator = (const String &other); // 赋值函数 :实现字符串的传值活动bool operator==(const String &str);      friend ostream & operator<<(ostream& o,const String &str);  private:char *m_data;}; String::String (const char *str) {if(str == NULL){m_data = new char[1];*m_data = '\0';}else{int length = strlen(str);m_data = new char[length+1];strcpy(m_data,str);} } String::String (const String &other) {int length = strlen(other.m_data );m_data = new char[length+1];strcpy(m_data,other.m_data ); } String::~String () {delete []m_data; } String &String:: operator = (const String &other) {if(this == &other)  //检查自赋值return *this;delete []m_data;  //释放原有的内存资源int length = strlen(other.m_data);m_data = new char[length+1];strcpy(m_data,other.m_data );return *this;   //返回本对象的引用 } bool String::operator==(const String &str)  {      return strcmp(m_data,str.m_data) == 0;  }  ostream & operator<<(ostream &o,const String &str)  {      o<<str.m_data;      return o;} int main() {  String s = "hello";         String s2 = s;         String ss = "hello";        cout<<"s = "<<s<<endl;        cout<<"s2 = "<<s2<<endl;   }#endif
阅读全文
0 0